eBash

It is not the mountain we conquer but ourselves

Project Euler Problem 17

| Comments

Table of Contents

1 Problem

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.

2 Solution

我们知道<1000的都可由,one,two…ninteen,twenty,thirty…ninety,hundred,and 这些英文字母表达出来,并将one~nineteen的字母数保存在数组 a[19]={3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8} 中,twenty,thirty..ninety的字母数保存在数组 b[8]={6, 6, 5, 5, 5, 7, 6, 6} 中,简单分类计算sum:

  1. \(i\in[1,20)\)
    sum = sum+ a[i - 1]
  2. \(i\in[20,100)\)
    1. sum = sum + b[i / 10 - 2] \(i\in\) {20,30,..90}
    2. sum = sum + b[i / 10 - 2] + a[i % 10 - 1] \(i\in\) {21,22,…99}
  3. \(i\in[100,1000)\)
    1. sum = sum + a[i / 100 - 1] + len(“hundred”) \(i\in\) {100,200,300..900}
    2. sum = sum + a[i / 100 - 1] + len(“hundred”) + len(“and”) + a[i % 100 - 1]; \(i\in\) {101-119,201-219,…901-919}
    3. sum = sum + a[i / 100 - 1] + len(“hundred”) + len(“and”) + b[i / 10 % 10 - 2]; \(i\in\) {120,130,140..990}
    4. sum = sum + a[i / 100 - 1] + len(“hundred”) + len(“and”) + a[i % 10 - 1] + b[i / 10 % 10 - 2]; \(i\in\) {121,122…999}
  4. \(i = 1000\)
    sum = sum + len(“one”) + len(“thousand”);

3 Answer

21124

Source:C++

Comments