Created
December 29, 2019 13:48
-
-
Save alysson-pina/6a27de407fd7fdd93345d7370412aba3 to your computer and use it in GitHub Desktop.
Calculate Binary of a given number (in base 10)
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
/** | |
* Calculate binary form of a given number n. | |
* | |
* Recursive implementation to calculate binary number for a given number. | |
* Algorithm is O(log(N)) on both performance and memory consumption. | |
* | |
* @param {number} n Number in base 10 | |
* | |
* @return {string} Binary representation of given number | |
*/ | |
function binaryOf(n) { | |
const binArray = new Array( Math.floor(Math.log2(n)) + 1 ).fill(0); // array to contain binary digits | |
calculateBinary(n, binArray); | |
return binArray.reverse().join(''); | |
} | |
function calculateBinary(n, bin) { | |
if(n < 2){ | |
bin[0] = n; | |
return; | |
} | |
const highestBit = Math.floor( Math.log2(n) ); | |
bin[highestBit] = 1; | |
calculateBinary(n - Math.pow(2, highestBit), bin); | |
} | |
export default binaryOf; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment