Skip to content

Instantly share code, notes, and snippets.

@mkamranhamid
Created June 5, 2020 12:59
Show Gist options
  • Save mkamranhamid/fbc286d7748ee56c97f4cb8421faaed1 to your computer and use it in GitHub Desktop.
Save mkamranhamid/fbc286d7748ee56c97f4cb8421faaed1 to your computer and use it in GitHub Desktop.
Find longest sequence of zeros in binary representation of an integer.
// codility test prep questions
// For example, number 9 has binary representation 1001 and contains a binary gap of length 2.
// The number 529 has binary representation 1000010001 and contains two binary gaps: one of length
// 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1.
// The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation
// 100000 and has no binary gaps.
function findFirstNumberOfZeroes(num){
var binary = num.toString(2);
var numberOfZeros = 0;
var stopped = false;
for(var i=1; i<binary.length;i++){
var chr = binary[i]
if(chr === '0'){
numberOfZeros += 1;
}
if(chr == '1'){
stopped = true
break;
}
}
return stopped ? numberOfZeros : 0;
}
findFirstNumberOfZeroes(15) // returns 0
findFirstNumberOfZeroes(20) // returns 1
findFirstNumberOfZeroes(529) // returns 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment