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 do
def binary n
Math.log2(n).floor.downto(0).select {|i| n[i] == 1 }.collect {|i| 2**i}
end
You could avoid the call to Math.log2 by calculating successive powers of 2 until that power was too big:
def binary n
bit = 0
two_to_the_bit = 1
result = []
while two_to_the_bit <= n
if n[bit] == 1
result.unshift two_to_the_bit
end
two_to_the_bit = two_to_the_bit << 1
bit += 1
end
result
end
more verbose, but faster
Here is a solution that uses Ruby 1.8. (Math.log2
was added in Ruby 1.9):
def binary(n)
n.to_s(2).reverse.chars.each_with_index.map {|c,i| 2 ** i if c.to_i == 1}.compact
end
In action:
>> def binary(n)
>> n.to_s(2).reverse.chars.each_with_index.map {|c,i| 2 ** i if c.to_i == 1}.compact
>> end
=> nil
>> binary(19)
=> [1, 2, 16]
>> binary(24)
=> [8, 16]
>> binary(257)
=> [1, 256]
>> binary(1000)
=> [8, 32, 64, 128, 256, 512]
>> binary(1)
=> [1]
Add a final .reverse
if you would like to see the values in descending order, of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With