Skip to content

Instantly share code, notes, and snippets.

@skiabox
Created January 25, 2020 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skiabox/96c6b3ede34eeb94ce7064794c2dcceb to your computer and use it in GitHub Desktop.
Save skiabox/96c6b3ede34eeb94ce7064794c2dcceb to your computer and use it in GitHub Desktop.
Binary Gap Algorithm in javascript ES6
//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