Can someone give the simplest solution to convert an integer into a Array of Integer representing its relevant binary digits..
Input => Output
1 => [1]
2 => [2]
3 => [2,1]
4 => [4]
5 => [4,1]
6 => [4,2]
One way is :
Step 1 : 9.to_s(2) #=> "1001"
Step 2 : loop with the count of digit
use / and %
based on loop index, multiply with 2
store in a array
Is there any other direct or better solution?
Fixnum and Bignum have a
[]method, that returns the value of the nth bit. With this we can doYou could avoid the call to Math.log2 by calculating successive powers of 2 until that power was too big:
more verbose, but faster