加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:00:18 所属栏目:百科 来源:网络整理
导读:有人可以提供最简单的解决方案将整数转换为表示其相关二进制数字的整数数组. Input = Output1 = [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 i
有人可以提供最简单的解决方案将整数转换为表示其相关二进制数字的整数数组.

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

更冗长,但速度更快

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读