计算 Bignum 中位数的方法

Way to count number of digits in a Bignum

我正在写一个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 分解成其组成数字的数组(这就是我要实现的)。

谢谢!

您可以将其转换为字符串并计算其大小

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]
x = 424723894070784320891478329472334238899
Math.log10(x).floor + 1 # => 39

Math.log10(x + 1).ceil # => 39