Number letter counts
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(three hundred and forty-two)包含23个字母,而115(one hundred and fifteen)包含20个字母。单词“and”的使用方式遵循英式英语的规则。
这个体通过把1-19分为一个区域,进行对1-19的英文字母的个数返回,把20-99化为一个区域,把100-999化为一个区域但是整百数也是一个特殊情况需要特殊处理,最后1000单独处理,这个题没有什么逻辑难度,主要是找规律以及对英文数组的理解,下面是代码实现:
#include <stdio.h> int arr1[20] = { 0, 3, 3, 5, 4 ,4, 3, 5, 5, 4, 3, 6, 6, 8 ,8 ,7, 7, 9, 8, 8 };//1-19的英文字母个数 int arr2[10] = { 0, 0, 6, 6, 5, 5, 5, 7, 6, 6 };//整10的英文字母个数 int get_lenght(int n) { if (n < 20) return arr1[n]; else if (n < 100) return arr2[n / 10] + arr1[n % 10]; else if (n < 1000) { if (n % 100 == 0) return arr1[n / 100] + 7; return arr1[n / 100] + 10 + get_lenght(n % 100); } return 11; } int main() { int ans = 0; for (int i = 1; i <= 1000; i++) ans += get_lenght(i); printf("%d\n", ans); return 0; }
最终答案:21124