我想编写一个采用整数和位长度的方法,并返回与这些位对应的整数数组。
例如:
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
注意:我不需要担心不是精确除数的位长。
答案 0 :(得分:2)
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]
答案 1 :(得分:0)
这个怎么样?
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