Created
July 2, 2018 06:23
-
-
Save andhikamaheva/44eddad3daad204f06d191aafe3b9ab6 to your computer and use it in GitHub Desktop.
Codility BinaryGap Exercise Solution (JavaScript/NodeJS)
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
// you can write to stdout for debugging purposes, e.g. | |
// console.log('this is a debug message'); | |
function solution(N) { | |
// write your code in JavaScript (Node.js 8.9.4) | |
let binary = (N >>> 0).toString(2); | |
let totalGaps = [] | |
let tmp = 0 | |
for (let i = 0; i < binary.length; i++) { | |
if (binary[i] === "0") { | |
if (binary.length - 1 === i) { | |
tmp = 0 | |
} | |
tmp ++ | |
} else if (binary[i] === "1" && i !== 0) { | |
totalGaps.push(tmp) | |
tmp = 0 | |
} | |
} | |
if (totalGaps.length === 0) { | |
return 0 | |
} else { | |
return Math.max.apply(null, totalGaps) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment