Last active
January 12, 2016 04:32
-
-
Save brianswisher/b8d0e72da6d4bedda3a1 to your computer and use it in GitHub Desktop.
Get the largest binary gap from a positive integer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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