Longest Consecutive Run of 1s in Binary
1 min readMar 3, 2021
Intuition
If we keep pushing the last element at the end we can iterate using binary. Next use masking by multiplying by 1 you can get whether the final bit is 1 or not.
Implementation
Take two counters runLength and a maxLength. while left shifting bit (like iteration but for binary) keep masking by 1 and figure out if it’s a 1 or 0 as the last digit. Keep checking if the runLength exceeds the maxLength (if yes the you have new max length). If the last digit has zero reset the run length. return the max length.
Time Complexity
O(n)we just have to iterate through bits one time
Space Complexity
O(1)constant amount of space required
Solution
class Solution {
solve(n) {
let runLength = 0;
let maxLength = 0;
while (n > 0) {
if (n & 1 === 1) {
runLength++;
} else {
runLength = 0;
}
if (runLength > maxLength) {
maxLength = runLength;
}
n = n >> 1
}
return maxLength;
}
}