我做在Ruby程序,我不知道爲什麼它不給我正確的答案歐拉項目#17紅寶石 - 怎麼了?
問題: 如果數字1至5字寫得出來:一,二,三,四,五,那麼總共使用3 + 3 + 5 + 4 + 4 = 19個字母。
如果所有從1到1000(包括1000)的數字都用文字寫出來,會用多少個字母?
注意:不要計算空格或連字符。例如,342(三百四十二)包含23個字母,115(一百一十五)包含20個字母。在編寫數字時使用「和」符合英國的用法。
我的代碼:
def number_to_words(n)
custom = {"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",}
tens = {"0" => "", "1" => "ten", "2" => "twenty", "3" => "thirty", "4" => "forty", "5" => "fifty", "6" => "sixty", "7" => "seventy", "8" => "eighty", "9" => "ninety"}
if n < 20
string = custom[n.to_s]
elsif n >= 20 && n < 100
string = tens[n.to_s[0]] + custom[n.to_s[1]]
elsif n % 1000 == 0
string = "onethousand"
elsif n >= 100 && n % 100 == 0
string = custom[n.to_s[0]] + "hundred"
else
string = custom[n.to_s[0]] + "hundred" + "and" + tens[n.to_s[1]] + custom[n.to_s[2]]
end
end
def letter_counter(x)
n = 1
sum = 0
while n < x + 1
sum = sum + number_to_words(n).length
print number_to_words(n).length, "\n"
n = n + 1
print n, "\n"
end
results = sum
end
正確答案是
這不完全匹配SO格式。你最好在http://codereview.stackexchange.com/ – phts 2015-04-06 12:19:42
@phts上提出這個問題,這是不正確的。此代碼無法按預期工作,因此無法用於代碼視圖。請閱讀:http://meta.stackoverflow.com/questions/253975/be-careful-when-recommending-code-review-to-askers。謝謝! – Vogel612 2015-04-06 12:21:12