Last active
December 2, 2019 18:15
-
-
Save tdous/40856aa4b1c787bd2b8579d5b0d64d1f to your computer and use it in GitHub Desktop.
Binary gap of decimal
This file contains 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
/** | |
* Get the "binary gap" if a given decimal, the maximal number of '0' | |
* between two '1' in the binary representation of a number. | |
* | |
* eg. 155 -> 10011011 - binary gap = 2 | |
* eg. 12112 -> 10111101010000 - binary gap = 1 | |
*/ | |
const getIntBinaryGap = decimal => { | |
// Convert to binary | |
const binaryStr = (decimal >>> 0).toString(2); | |
// Trim edge zeroes, split by 1 | |
return Math.max( | |
...binaryStr | |
.replace(/^0+|0+$/g, '') | |
.split('1') | |
.filter(i => true) | |
.map(i => i.length) | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment