Rubyで桁の合計を求める 〜Rubyでオイラープロジェクトを解こう!Problem16
and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number ?
の各桁の合計は 3 + 2 + 7 + 6 + 8 = 26である。
の各桁の合計はいくつか。
算数的でないけど
def sum_of_digits(n) n.to_s.split("").map { |s| s.to_i }.inject(:+) end sum_of_digits(2**1000) # => 1366
もう少し算数的に
def sum_of_digits(n) sum = 0 begin n, b = n.divmod(10) sum += b end until n == 0 and b == 0 sum end sum_of_digits(2**1000) # => 1366