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.
如果数字1到5用英字写出:一(one),二(two),三(three),四(four),五(five),则总共使用3 + 3 + 5 + 4 + 4 = 19个字母。
如果所有1到1000(一千)的数字都用文字写出来,会用多少个字母?
注意:不要计算空格或连字符。例如,342(三百四十二)包含23个字母,115(一百一十五)包含20个字母。在写出数字时使用“和”符合英国的用法。
思路
1.找规律:
(1)用两个数组分别把20以内所对应的英文,以及整十的数字记录下来;
(2)设定字符长度函数;
#include <stdio.h>
int num1[20] = {0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,8,8};
int num2[10] = {0,0,6,6,5,5,5,7,6,6};
int len(int num){
if(num < 20){
return num1[num];
}else if(num < 100){
return num1[num % 10] + num2[num /10];
}else if(num < 1000){
if(num % 100 == 0){
return num1[num / 100] + 7;
}else{
return num1[num / 100] + len(num % 100) + 10;
}
}else{
return 11;
}
}
int main(){
int sum = 0;
for(int i = 1; i <= 1000; ++i){
sum += len(i);
}
printf("%d\n", sum);
return 0;
}