The task
Given an integer n, return the length of the longest consecutive run of 1s in its binary representation.
For example, given 156, you should return 3
My function solution 1
Style 1
function findMaxNumberOfConsecOnes(dec){
const countConsecOnes = (acc, x) => [acc[0] < acc[1]
? acc[1]
: acc[0],
x === "1"
? acc[1] + 1
: 0 ];
return [...(dec >>> 0).toString(2)]
.reduce(countConsecOnes, [0,0]);
}
Style 2
function findMaxNumberOfConsecOnes(dec){
const countConsecOnes = (acc, x) => [acc[0] < acc[1] ? acc[1] : acc[0],
x === "1" ? acc[1] + 1 : 0 ];
return [...(dec >>> 0).toString(2)]
.reduce(countConsecOnes, [0,0]);
Style 1 and Style 2 have the exact same logic, but different style. My first idea was to write it in Style 1. But I then thought what was said to me in this thread about indentation. Therefore I opt for Style 2. But still not sure, whether this is the right way.
Alternatively:
My functional Solution 2
function findMaxNumberOfConsecOnes(dec){
return [...(dec >>> 0).toString(2)]
.reduce((acc, x) => {
const current = x === "1" ? acc[1] + 1 : 0;
const max = Math.max(acc[0], current);
return [max, current];
}, [0,0]);
}
My imperative Solution
function findMaxNumberOfConsecOnes(dec){
const binStr = (dec >>> 0).toString(2);
let max = 0, current = 0;
for (const s of binStr) {
current = s === "1" ? current + 1 : 0;
max = Math.max(max, current);
}
return max;
}