【问题标题】:Decomposing an integer into an array of integers by bit manipulation通过位操作将整数分解为整数数组
【发布时间】:2012-09-30 00:52:11
【问题描述】:

我想写一个方法,它接受一个整数和一个位长度,并返回一个与位对应的整数数组。

例如:

decompose(100, 4)
#=> [4, 12]

because:

100 is 01001100 in binary
        /   \
      0100  1100
       4      12

decompose(123456, 6)
#=> [1, 8, 60, 0]

because:

123456 is 000001001000111100000000 in binary
           /       |     |      \
          1        8     60      0

注意:我不需要担心不是精确除数的位长度。

【问题讨论】:

  • 我认为您的号码不正确。

标签: ruby integer bit-manipulation


【解决方案1】:
def decompose n, l, a = []
  n, r = n.divmod(2 ** l)
  a.unshift(r)
  n.zero? ? a : decompose(n, l, a)
end

decompose(100, 4) # => [6, 4]
decompose(123456, 6) # => [30, 9, 0]

【讨论】:

    【解决方案2】:

    这个怎么样?

    def decompose(num, len)
      num.to_s(2).chars.each_slice(len).map { |x| x.join.to_i(2) }.reverse
    end
    
    decompose(100, 4)
    #=> [4, 12]
    

    或者这个:

    def decompose(num, len)
      num.to_s(2).scan(/.{1,len}/).map { |x| x.to_i(2) }.reverse
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      • 2016-11-28
      • 2023-03-28
      • 1970-01-01
      • 2017-07-24
      相关资源
      最近更新 更多