Last active
July 6, 2019 16:51
-
-
Save k0ff33/6f8cbcbac3cf7744535087d7ed0b4a0c to your computer and use it in GitHub Desktop.
Binary Gap Exercise from Codility (JavaScript/NodeJS)
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
/** | |
* Function which calculates the binary gap of the integer N | |
* @param {int} N | |
* @return {int} result | |
*/ | |
function solution(N) { | |
// Convert decimal to binary | |
let binary = (N >>> 0).toString(2) | |
// Check if Regex matched results (array is not null) | |
let arrOfZeros = binary.match(/(?!1)(0+)/g) | |
// Then sort the array based on item length | |
// Return first entry (longest) | |
// Or return 0 if array is empty/null | |
let result = (arrOfZeros) ? arrOfZeros.sort((a, b) => a.length < b.length)[0].length : 0 | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment