binary gap
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.
by bob m
HTML
<!-- see https://codility.com/programmers/lessons/1-iterations/binary_gap/ -->
<p id="gap">
Let's get started
</p>
JavaScript
function binaryGap(n){
if (n==undefined) { return 0;}
var binary = n.toString(2); console.log(binary);
var left = false; var right = false;
var numGaps = 0; var maxGaps = 0;
for (i=0; i < binary.length-1; i++){
console.log('i = ' + i + '; binary char is : ' + binary[i]);
if (binary[i]=='1' && binary[i+1]=='0'){
if (!left){
left=true;
continue;
}
}
if (binary[i]=='0' && left){
numGaps++;
}
if (binary[i]=='1' && left){ // gap is closed, this "1" now becomes left
left = true;
maxGaps = numGaps; console.log('char is 1 and left is on, i = ' + i);
}
if (i == binary.length-2 && binary[i+1]=='0'){ // peek ahead to the last char
}
}
return maxGaps;
}
var n=48; var result = binaryGap(n);
document.getElementById("gap").innerHTML = "bin gap of " + n.toString(2) + " is : " + result;