Skip to content

Instantly share code, notes, and snippets.

@Tynael
Last active March 22, 2018 08:06
Show Gist options
  • Save Tynael/59fc650b6d6c21c75293c647a6ed842a to your computer and use it in GitHub Desktop.
Save Tynael/59fc650b6d6c21c75293c647a6ed842a to your computer and use it in GitHub Desktop.
// Finds the length of the longest consecutive 1s
// in a binary representation of a given number.
function maxConsecutiveOnes(x)
{
// Initialize result
let count = 0;
while (x != 0)
{
x &= (x << 1);
count++;
}
return count;
}
// Inverts maxConsecutiveOnes to return the longest
// consecutive 0s
// NOT WORKING
function maxConsecutiveZeros(x)
{
return maxConsecutiveOnes(~x);
}
console.log(maxConsecutiveZeros(29));
//
function maxConsecutiveZeros(inputNumber) {
let maxGap = 0;
let currentMaxGap = 0;
let binStr = inputNumber.toString(2);
let startIndexFromEnd = binStr.length - 1;
for (startIndexFromEnd; startIndexFromEnd >= 0; startIndexFromEnd--) {
if (binStr.charAt(startIndexFromEnd) != '0') {
break;
}
}
for (let i = startIndexFromEnd - 1; i >= 0; i--) {
if (binStr.charAt(i) == '0') {
currentMaxGap = currentMaxGap + 1;
} else {
if (currentMaxGap > maxGap) {
maxGap = currentMaxGap;
}
currentMaxGap = 0;
}
}
return maxGap;
}
maxConsecutiveZeros(125345);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment