xxxxxxxxxx
let N = 9;
const Binary = N.toString(2); // "1001"
const BinaryArray = Binary.split(''); // ["1", "0", "0", "1"]
// finding the first one via its index
const firstOne = BinaryArray.indexOf("1"); // 0 = Index of array
// new array created taking a slice of original array
// from the index of the firstOne + 1 index
let NewBinaryArray = BinaryArray.slice(firstOne + 1);
// ["0", "0", "1"]
// finding second one via its index in new array slice
const secondOne = NewBinaryArray.indexOf("1"); // 2
// where we store our gaps
const gaps = [];
// adding 2 to our gaps array
gaps.push(secondOne); // [2]
// getting largest value in array
return Math.max.apply(Math, gaps); // 2
xxxxxxxxxx
function findBinaryGap(N) {
const binaryNumber = N.toString(2);
const gaps = [];
let currentOne;
let currentOneIterator = -1;
while(true){
currentOne = binaryNumber.indexOf('1', currentOneIterator + 1);
const nextOne = binaryNumber.indexOf('1', currentOne + 1);
if(nextOne < 0 || currentOne < 0){
break;
}
gaps.push(nextOne - (currentOne + 1));
currentOne = nextOne;
currentOneIterator += 1
}
return !!gaps.length ? Math.max.apply(null, gaps) : 0;
}
const binaryGap = findBinaryGap(1610612737);
//result will be 28