Daily Coding Day Two Fourteen

This question, according to the email, was asked by Stripe. It’s a unique question, binary is always fun.

Question: 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.

They don’t say this but that is because 156 is 10011100

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function longestConsecutiveOnes(n) {
// JS has a to binary with toString(2)
const binary = n.toString(2);

// Split and get the 1s
const onesGroups = binary.split('0');

// Find the max
let maxLength = 0;
for (const group of onesGroups) {
maxLength = Math.max(maxLength, group.length);
}

return maxLength;
}

// Tests
console.log(longestConsecutiveOnes(156)); // Output: 3 (binary: '10011100')
console.log(longestConsecutiveOnes(222)); // Output: 4 (binary: '11011110')
console.log(longestConsecutiveOnes(15)); // Output: 4 (binary: '1111')
console.log(longestConsecutiveOnes(128)); // Output: 1 (binary: '10000000')