Skip to content

Instantly share code, notes, and snippets.

@erkanzileli
Created April 21, 2019 21:40
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 erkanzileli/5ec42f2be0a47efda0331680ac7ae3d5 to your computer and use it in GitHub Desktop.
Save erkanzileli/5ec42f2be0a47efda0331680ac7ae3d5 to your computer and use it in GitHub Desktop.
JavaScript binary gap solution
/**
* Services:
* 1 - Convert integer to binary string
* 2 - Find binary gaps from binary string and add to custom data struct
* 3 - Get biggest binary gaps
*/
function binaryGap(N) {
// get binary string
var binaryString = N.toString(2);
// find binary gaps
var binaryGaps = {};
var isBinaryGap = false;
var binaryGapCounter = 0;
var binaryGapIndex = 0;
for (let i = 0; i < binaryString.length - 1; i++) {
const current = binaryString[i];
const next = binaryString[i + 1];
if (current == 1 && next == 0) {
// start the binary gap situation
isBinaryGap = true;
binaryGapCounter = 1;
continue;
}
if (isBinaryGap) {
if (next == 1) {
// finish counting
isBinaryGap = false;
binaryGaps[binaryGapIndex.toString()] = binaryGapCounter;
binaryGapCounter = 0;
binaryGapIndex++;
} else {
// increment binary gap
binaryGapCounter++;
}
}
}
return (
Object.values(binaryGaps).sort((a, b) => {
if (a < b) return 1;
else if (a > b) return -1;
else return 0;
})[0] || 0
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment