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.


In [3]:
def pro_one(num) # 1..19
    return "" if num == 0
    %w(zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen)[num]
  end
  
  pro_one(5)


Out[3]:
"five"

In [4]:
def pro_ten(num) # 20..99
    return pro_one(num) if num < 20
    tens = %w(zero ten twenty thirty forty fifty sixty seventy eighty ninety)
    
    ten, one = num.to_s.split("").map{|i|i.to_i}
    return tens[ten] + " " + pro_one(one)
  end
  
  pro_ten(56)


Out[4]:
"fifty six"

In [5]:
def pro_hundred(num) #100..999
  return pro_ten(num) if num < 100
  return "one thousand" if num == 1000
  hun, ten_one = [num.to_s[0].to_i, num.to_s[1..2].to_i]
  return pro_one(hun) + " hundred and " + pro_ten(ten_one) if ten_one != 0
  return pro_one(hun) + " hundred"
end

pro_hundred(430)


Out[5]:
"four hundred and thirty "

In [6]:
(1..1000).to_a.map{|i| pro_hundred(i).gsub(/[ \-]/, "").length }.inject &:+


Out[6]:
21124

In [7]:
pro_hundred(115).gsub(/[ \-]/, "").length


Out[7]:
20

In [ ]: