[Project Euler] 来做欧拉项目练习题吧: 题目017

时间:2021-08-20 19:03:28

                [Project Euler] 来做欧拉项目练习题吧: 题目017

                              周银辉

 

题目描述:

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.

 

问题分析:

这个题目比较简单哈,用铅笔和纸也比如容易算出啦。比如计算单个数字的出现次数,"hundred"单词出现的次数等等。

而用程序计算嘛,关键在于创建一个数字和对应单词长度的映射,也就是上面numbers那个数组。

然后分离出百位数、十位数、个位数,以及处理各种特殊情况就可以了。

 

#include <stdio.h>

int numbers[91];

void ini_numbers()
{
//为了节省空间,用hash_map也可以

numbers[0] = 0;//no pronunciation for zero 
numbers[1] = 3;//"one"
numbers[2] = 3;//"two"
numbers[3] = 5;//"three"
numbers[4] = 4;//"four"
numbers[5] = 4;//"five"
numbers[6] = 3;//"six"
numbers[7] = 5;//"seven"
numbers[8] = 5;//"eight"
numbers[9] = 4;//"nine"
numbers[10] = 3;//"ten"
numbers[11] = 6;//"eleven"
numbers[12] = 6;//"twelve"
numbers[13] = 8;//"thirteen"
numbers[14] = 8;//"fourteen"
numbers[15] = 7;//"fifteen"
numbers[16] = 7;//"sixteen"
numbers[17] = 9;//"seventeen"
numbers[18] = 8;//"eighteen"
numbers[19] = 8;//"nineteen"
numbers[20] = 6;//"twenty"
numbers[30] = 6;//"thirty"
numbers[40] = 5;//"forty"
numbers[50] = 5;//"fifty"
numbers[60] = 5;//"sixty"
numbers[70] = 7;//"seventy"
numbers[80] = 6;//"eighty"
numbers[90] = 6;//"ninety"
}

int get_length(int n)
{
int a=0; //hundreds'digit
int b=0; //ten's digit
int c=0; //units' digit
int length = 0;

a = n/100;
n = n%100;
b = n/10;
c = n%10;
if(a!=0)
{
length += numbers[a] + 7; // 7 for "hundred"
if(b!=0 || c!=0)
{
length += 3; //3 for "and"
}
}

if(b!=0)
{
if(b==1)
{
length += numbers[b*10+c];
return length;
}
else
{
length += numbers[b*10];
}
}

if(c!=0)
{
length += numbers[c];
}

return length;
}

int main()
{
int i, length=0;

ini_numbers();

for(i=1; i<=999; i++)
{
length += get_length(i);
}

length += 11; //11 for "one thousand"

printf("total length: %d\n", length);
return 0;

}