如何将整数转换为二进制数组..

Rak*_*esh 4 ruby ruby-on-rails

有人可以提供最简单的解决方案将整数转换为表示其相关二进制数字的整数数组.

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
Run Code Online (Sandbox Code Playgroud)

还有其他直接或更好的解决方案吗?

Fre*_*ung 8

Fixnum和Bignum有一个[]方法,它返回第n位的值.有了这个我们就能做到

def binary n
  Math.log2(n).floor.downto(0).select {|i| n[i] == 1 }.collect {|i| 2**i}
end
Run Code Online (Sandbox Code Playgroud)

您可以通过计算2的连续幂来避免对Math.log2的调用,直到该功率太大为止:

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
Run Code Online (Sandbox Code Playgroud)

更冗长,但速度更快