Skip to content

Instantly share code, notes, and snippets.

@k0ff33
Last active July 6, 2019 16:51
Show Gist options
  • Save k0ff33/6f8cbcbac3cf7744535087d7ed0b4a0c to your computer and use it in GitHub Desktop.
Save k0ff33/6f8cbcbac3cf7744535087d7ed0b4a0c to your computer and use it in GitHub Desktop.
Binary Gap Exercise from Codility (JavaScript/NodeJS)
/**
* 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