Problem 017

Project Euler

Number letter counts

Problem 17

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.

This problem can be breakdown into sub problem of finding the total letter of 1-9, 10 -19, 20-99, 100-999 and 1000. The total letter of 1-9 should be calculated first and reuse it on subsequent calculation.

For example, let sumOneToNine = the total letter of 1-9, and sumOfEveryTen = total letter of “TWENTY”, “THIRTY”, … , “NINETY”, then the total letter of 20-99 is:

  sumOf20To99 = (sumOneToNine * 8) + (sumOfEveryTen * 10)

This is because the word “ONE” is being counted in 21, 31 … 91 (8x) for all unit digit from 1 – 9. For every ten values, the same “-TY” word is being repeated 10 times such as 20, 21, 22 … 29.  Similarly, repeat this strategy to minimize looping through all the numbers for the other ranges.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s