Created
October 11, 2019 09:05
-
-
Save flangofas/2a355294b9f1c9679b511db1f7475685 to your computer and use it in GitHub Desktop.
Write a function for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11
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
//Reverse Binary | |
//Useful link: https://aticleworld.com/5-way-to-reverse-bits-of-an-integer/ | |
let decimal = process.argv[2] | |
if (typeof decimal === "undefined") { | |
throw new Error('Please provide a decimal number'); | |
} | |
console.log(reverseBits(new Number(decimal))) | |
/** | |
* Convert a number to binary and then reverse its bits. | |
* | |
* @param Number n | |
* @return Number | |
*/ | |
function reverseBits(n) | |
{ | |
let binary = (n >>> 0).toString(2) | |
let reverseBinary = binary.split('').reverse().join('') | |
return parseInt(reverseBinary, 2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment