Last active
May 31, 2016 07:37
-
-
Save dolvik/3f6fdebc293c3d371144 to your computer and use it in GitHub Desktop.
Binary gap
This file contains hidden or 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
//Find longest sequence of zeros in binary representation of an integer. | |
function solution(n) { | |
var str = toBinaryString(n).replace(/0+$/, ""); | |
var arr = str.split("1").filter(function(e) { return e.length > 0; }); | |
if (arr.length === 0){ | |
return 0; | |
} | |
arr.sort(function(a, b){ return b.length - a.length; }); | |
return arr[0].length; | |
} | |
function solution2(n) { | |
//get binary string | |
var str = toBinaryString(n); | |
console.log(str); | |
var re = /(0+?)1/g; | |
var ex; | |
var result = []; | |
//find groups | |
while (ex = re.exec(str)){ | |
//console.log(ex[1]); | |
result.push(ex[1]); | |
} | |
if (!result.length){ | |
return 0; | |
} | |
//sort groups descending | |
result.sort().reverse(); | |
return result[0].length; | |
} | |
console.log(solution2(41104)); //1010000010010000 - 5 | |
console.log(solution2(127)); //1111111 - 0 | |
function toBinaryString(n){ | |
return (n >>> 0).toString(2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment