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 the final .reverse if you want to see the values ββin descending order, of course.
source share