ruby-on-rails - 如何将整数转换为二进制数组...

标签 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

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

最佳答案

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

更冗长,但更快

关于ruby-on-rails - 如何将整数转换为二进制数组...,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11389463/

相关文章:

ruby-on-rails - 设计和双重安全

mysql - 在 Rails 中使用存储过程

ruby-on-rails - 生产中的 `config.requre_master_key = false` 是否会导致任何问题?

ruby-on-rails - 为什么 Rails 拒绝使用我的模型(基于 SQL View )?

ruby - 在 Enumerable#each_cons 中跳过 'n' 次迭代

ruby - irb 转义双引号的行为

ruby-on-rails - 使用 has_many :through and build

sql - 使用 Ruby Geocoder 检索附近的用户和返回距离

ruby - 使用 Apache 托管 Ruby gem

ruby - gedit 中的语法突出显示不会自动工作