Last active
March 22, 2018 08:06
-
-
Save Tynael/59fc650b6d6c21c75293c647a6ed842a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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