我正在编写一个ruby方法,如下所示:
def build_array(word)
word_copy = word
array = []
length = word_copy.length
for i in 1..length do
array[i] = word_copy % 10
word_copy = word_copy/10;
end
puts array
end
我想创建一个迭代器,它从1计数到Bignum
中的位数。
Bignum.length
不是有效的ruby。或者,有没有一种方法可以将Bignum
分解为其组成数字的数组(这就是我试图实现的)。
谢谢!
x = 424723894070784320891478329472334238899
Math.log10(x).floor + 1 # => 39
或
Math.log10(x + 1).ceil # => 39
您可以将其转换为字符串并计算其大小
b = 2_999_999_000_000_000
p b.class
#=> Bignum
p b.to_s.size
#=> 16
p b.to_s.split("").map(&:to_i)
#=> [2, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0]