Skip to content

Instantly share code, notes, and snippets.

@tdous
Last active December 2, 2019 18:15
Show Gist options
  • Save tdous/40856aa4b1c787bd2b8579d5b0d64d1f to your computer and use it in GitHub Desktop.
Save tdous/40856aa4b1c787bd2b8579d5b0d64d1f to your computer and use it in GitHub Desktop.
Binary gap of decimal
/**
* 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