gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:23:14 26 4
gpt4 key购买 nike

谁能给出最简单的解决方案,将整数转换为表示其相关二进制数字的整数数组..

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com