Last active
January 18, 2024 14:22
-
-
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
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 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); | |
} |
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 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