Skip to content

Instantly share code, notes, and snippets.

@skiabox skiabox/app.js
Created Jan 25, 2020

Embed
What would you like to do?
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
You can’t perform that action at this time.