Skip to content

Instantly share code, notes, and snippets.

@brianswisher
Last active January 12, 2016 04:32
Show Gist options
  • Save brianswisher/b8d0e72da6d4bedda3a1 to your computer and use it in GitHub Desktop.
Save brianswisher/b8d0e72da6d4bedda3a1 to your computer and use it in GitHub Desktop.
Get the largest binary gap from a positive integer
(function(input){
function getLargestBinaryGap(n) {
var input = (function(){
if(typeof n !== "number"){
throw new Error("argument is not a number.")
}
if(n < 0){
throw new Error("argument is less than zero.")
}
return {
toBinary: function(){
n = (n).toString(2);
return this
},
toGaps: function(gap){
gap = 0;
n.split("").map(function(d){
if (typeof n !== "object") n = [];
if (d === "1") {
if (gap) {
n[n.length] = gap;
}
gap = 0;
} else {
gap++;
}
});
return this
},
getLargest: function(){
if (!n.length) return 0;
n.sort();
return n.pop()
}
}
})();
return input
.toBinary()
.toGaps()
.getLargest()
}
return getLargestBinaryGap(input)
})(529)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment