Created
April 21, 2019 21:40
-
-
Save erkanzileli/5ec42f2be0a47efda0331680ac7ae3d5 to your computer and use it in GitHub Desktop.
JavaScript binary gap solution
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
/** | |
* 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