Thalatta
Thalatta

Reputation: 4578

Way to count number of digits in a Bignum

I am writing a ruby method as follows:

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

I would like to create an iterator which counts from 1 to the number of digits in a Bignum.

Bignum.length is not valid ruby. Alternatively, is there a way to bust up a Bignum into an array of its constituent digits (Which is what I am trying to implement).

Thanks!

Upvotes: 0

Views: 621

Answers (2)

sawa
sawa

Reputation: 168071

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

or

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

Upvotes: 3

Wand Maker
Wand Maker

Reputation: 18762

You could convert it to String and count its size

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]

Upvotes: 2

Related Questions