Skip to content

Instantly share code, notes, and snippets.

@nwrox
Last active July 6, 2017 13:14
Show Gist options
  • Save nwrox/c397106203c9fecfbfbc82b044391e11 to your computer and use it in GitHub Desktop.
Save nwrox/c397106203c9fecfbfbc82b044391e11 to your computer and use it in GitHub Desktop.
Desafio decimal para binário
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)
@suissa
Copy link

suissa commented May 5, 2017

Corrigido:

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)

@suissa
Copy link

suissa commented May 5, 2017

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