Skip to content

Instantly share code, notes, and snippets.

@clarketm
Last active October 12, 2022 12:13
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save clarketm/2d1f83a1f117d4d36cf24a05712a857e to your computer and use it in GitHub Desktop.
Save clarketm/2d1f83a1f117d4d36cf24a05712a857e to your computer and use it in GitHub Desktop.
Largest Binary Gap (JavaScript)
function largestBinaryGap(num) {
var bin = Math.abs(num).toString(2),
finalMax = 0,
currentMax;
for (var i = 0; i < bin.length; i++) {
currentMax = 0;
while (bin[i] === "0") {
++currentMax && ++i;
}
finalMax = Math.max(finalMax, currentMax);
}
return finalMax;
}
console.log(largestBinaryGap(1)); // 1 //=> 0
console.log(largestBinaryGap(5)); // 101 //=> 1
console.log(largestBinaryGap(6)); // 110 //=> 1
console.log(largestBinaryGap(19)); // 10011 //=> 2
console.log(largestBinaryGap(1041)); // 10000010001 //=> 5
console.log(largestBinaryGap(6291457)); // 11000000000000000000001 //=> 20
console.log(largestBinaryGap(1376796946)); // 1010010000100000100000100010010 //=> 5
console.log(largestBinaryGap(1610612737)); // 1100000000000000000000000000001 //=> 28
@Maulik3110
Copy link

Maulik3110 commented Oct 12, 2022

This is my solution with very less code and no direct loops

  function solution(N) {
      const binnum = Number(N).toString(2);
      let str = binnum.split('1');
      const newarr = str.filter(function(item,index){
          if (item === ''){
          }else if (index === str.length -1) {
          }else {
              return item;
          }
      })
      return newarr.length > 0 ? newarr.sort()[newarr.length -1].length : 0;
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment