LoginSignup
0
0

More than 1 year has passed since last update.

Rubyで数字を1行になるまで掛け算する

Posted at

前提

引数のintegerの値を一桁になるまで掛け続けて、何回掛け算を行ったかを返り値にする。

ex
39 --> 3 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit)

判定メソッド

def persistence(number)
  count = 0

  while number > 9 do
    num = 1
    number.to_s.split('').each do |i|
      num = num * i.to_i
    end

    number = num
    count += 1
  end

  count
end
def persistence(n)
  k = 0
   while n > 9 do
    n = n.to_s.split(//).map{|x| x.to_i}.inject(:*)
    k+=1
   end
  k 
end
def persistence(n)
  n < 10 ? 0 : 1 + persistence(n.to_s.chars.map(&:to_i).reduce(:*))
end
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0