Created
March 29, 2020 02:21
-
-
Save attilaking/b735659b0f9763d46c9aaac66d766072 to your computer and use it in GitHub Desktop.
[count Binary gap of an integer] Binary gap count #binary #binary gap
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
function binaryGap(N) { | |
let str = N.toString(2); | |
let startPos; | |
let endPos; | |
let res = []; | |
res.push(0); | |
console.log(str) | |
for (let i = 1; i < str.length; i++) { | |
if ((str.charAt(i) == '0' && str.charAt(i - 1) == '1')) { startPos = i } | |
if ((str.charAt(i) == '1' && str.charAt(i-1) == '0')) { | |
endPos = i; | |
res.push(endPos - startPos) | |
endPos = 0; | |
startPos = 0; | |
} | |
} | |
console.log(res) | |
return Math.max(...res); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment