Created
January 25, 2020 15:17
-
-
Save skiabox/96c6b3ede34eeb94ce7064794c2dcceb to your computer and use it in GitHub Desktop.
Binary Gap Algorithm in javascript ES6
This file contains 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
//A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. | |
const toBinaryString = number => { | |
return number.toString(2); // returns a string | |
}; | |
function solution(N) { | |
const nBinaryString = toBinaryString(N); | |
let numberOfZeroes = 0; | |
let max = 0; | |
// loop through letters | |
for (let i = 0; i < nBinaryString.length; i++) { | |
if (nBinaryString.charAt(i) === '1') { | |
if (numberOfZeroes > max) { | |
max = numberOfZeroes; | |
} | |
numberOfZeroes = 0; | |
continue; | |
} else { | |
numberOfZeroes++; | |
} | |
} | |
return max; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment