Skip to content

Instantly share code, notes, and snippets.

@fatehMohamed14
Last active January 18, 2024 14:22
Show Gist options
  • Save fatehMohamed14/b0fe22dc6adfa807f80c980ae50bad18 to your computer and use it in GitHub Desktop.
Save fatehMohamed14/b0fe22dc6adfa807f80c980ae50bad18 to your computer and use it in GitHub Desktop.
BinaryGap Codility solution, A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N
function solution(N) {
const binary = N.toString(2);
let gaps = [];
let count = 0;
for(let b of binary) {
if(b === "0") {
count++
} else {
gaps.push(count);
count = 0
}
}
return Math.max(...gaps);
}
function solution(N) {
const binary = N.toString(2);
let gaps = binary.match(/(?!1)(0+)(?=1)/g);
if(!gaps) {
return 0;
}
gaps = gaps.map(e => e.length);
return Math.max(...gaps);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment