読者です 読者をやめる 読者になる 読者になる

mu chance or much chance ?

日々の戯れ言

Project Euler 17

Project Euler

Problem17を解きました.

  • Number letter counts

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.

https://projecteuler.net/problem=17

問題は「1から1000までの数字をすべて英単語で書いた場合,全部で何文字になるか」.

$hash = {"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", "1000" => "onethousand"}

def getCountNumber(num)
	count = 0
	amari100 = num % 100
	if amari100 > 0 && amari100 < 20 then
		count += $hash[amari100.to_s].length
	elsif amari100 >= 20 then
		keta10 = amari100 / 10
		amari10 = amari100 % 10
		count += $hash[(keta10 * 10).to_s].length
		if amari10 != 0 then
			count += $hash[amari10.to_s].length
		end
	end
	keta100 = num / 100
	if keta100 == 10 then
		count += $hash[1000.to_s].length
	elsif keta100 > 0 && keta100 < 10 then
		count += $hash[keta100.to_s].length	
		count += $hash[100.to_s].length	
		if amari100 != 0 then
			count += 3 # "and"の3文字
		end
	end
	return count
end

tortal = 0
for i in 1..1000 do
	tortal += getCountNumber(i)
end

p tortal