Project Eueler: problem16

問題

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?

回答

def calc(num)
  2**num
end

def do_sum(num)
  sum = 0
  str = num.to_s
  0.upto(str.size.to_i-1) do |n|
    sum += str[n,1].to_i
  end
  sum
end

n = 15
p "sum = #{do_sum(calc(n))}"
n = 1000
p "sum = #{do_sum(calc(n))}"

備考

無駄が多いなぁ。
他の人を参考に。

(2**1000).to_s.split(//).inject(0){|sum,x| sum + x.to_i}

Rubyだと桁数大きくてもOKだけど、CやJavaだと大変みたい。