Problem 17 (Project Euler) [和訳])
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.
スペルミスにはくれぐれもご注意。私などは"tweleve"とやっているのに気づかなくて時間を喰いました。
コード量が、比較的短くて済んだので載せておきます。
begin_time = Time.now
num_hash = {0 => "", 1 => "one", 2 => "two", 3 => "three", 4 => "four",
5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine",
10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen",
14 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen",
18 => "eighteen", 19 => "nineteen", 20 => "twenty", 30 => "thirty",
40 => "forty", 50 => "fifty", 60 => "sixty", 70 => "seventy",
80 => "eighty", 90 => "ninety", 100 =>"hundred"}
sum = "one".length + "thousand".length
(1..999).each do |i|
h = (i / 100).floor # 100の位の数
o = i % 10 # 1の位の数
t = i % 100 - o # 10の位の数*10
if h > 0
sum += num_hash[h].length + num_hash[100].length
sum += "and".length unless t == 0 && o == 0
end
if t < 20
sum += num_hash[t+o].length
else
sum += num_hash[t].length + num_hash[o].length
end
end
puts "Char Num : #{sum}"
puts " -- #{Time.now - begin_time}sec"