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

时间:2012-07-09 05:22:55

标签: ruby-on-rails ruby

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

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

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

3 个答案:

答案 0 :(得分:8)

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

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

你可以通过计算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

更详细,但更快

答案 1 :(得分:3)

这是一个使用Ruby 1.8的解决方案。 ({1.9}中添加了Math.log2

def binary(n)
  n.to_s(2).reverse.chars.each_with_index.map {|c,i| 2 ** i if c.to_i == 1}.compact
end

行动中:

>>  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]

如果您希望按降序查看值,请添加最终.reverse

答案 2 :(得分:0)

class Integer
  def to_bit_array
    Array.new(size) { |index| self[index] }.reverse!
  end

  def bits
    to_bit_array.drop_while &:zero?
  end

  def significant_binary_digits
    bits = self.bits
    bits.each_with_object(bits.count).with_index.map do |(bit, count), index|
      bit * 2 ** (count - index - 1)
    end.delete_if &:zero?
  end
end

改编自these solutions found in comp.lang.ruby

一些简单的基准测试表明this solution比涉及base-2 logarithmsstring manipulation且慢于direct bit manipulation的算法更快。