Last active
July 6, 2017 13:14
-
-
Save nwrox/c397106203c9fecfbfbc82b044391e11 to your computer and use it in GitHub Desktop.
Desafio decimal para binário
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
const getLog2 = (n) => Math.round(Math.log2(n)) | |
const reverseSeq = (n) => Array.from(Array(n + 1).keys()).reverse() | |
const getPow = (b, n) => Math.pow(b, n) | |
const decToBin = (n) => { | |
reverseSeq(getLog2(n)).reduce( | |
(acc, curr) => (getPow(2, curr) <= n) ? ( n -= getPow(2, curr), acc + '1' ) : acc + '0', '' | |
) | |
} | |
const b = decToBin(257) | |
console.log(b) |
Melhorei:
const getLog2 = ( n ) => Math.round( Math.log2(n ) )
const reverseSeq = ( n ) => Array.from( Array( n + 1 ).keys() ).reverse()
const getPow = ( b, n ) => Math.pow( b, n )
const toBin = ( n ) => ( acc, curr ) =>
(getPow(2, curr) <= n)
? ( n -= getPow(2, curr), acc + '1' )
: acc + '0'
const decToBin = (n) =>
reverseSeq( getLog2( n ) ).reduce( toBin( n ), '' )
const b = decToBin(257)
console.log(b)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Corrigido: