Skip to content

Instantly share code, notes, and snippets.

@andhikamaheva
Created July 2, 2018 06:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andhikamaheva/44eddad3daad204f06d191aafe3b9ab6 to your computer and use it in GitHub Desktop.
Save andhikamaheva/44eddad3daad204f06d191aafe3b9ab6 to your computer and use it in GitHub Desktop.
Codility BinaryGap Exercise Solution (JavaScript/NodeJS)
// 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