将1……n的数表示成英文,求表示成这些英文的字母的和
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-19直接替换,然后20,30,40,50,60,70,80,90均有一个英文字符
当数字超过100且不是整数时,需要加上hundred和and10个字母
当数字超过100是整数时,值家hundred7个字母
当数字是1000时,直接的one thousand11个字母
如果有耐心,可以好好的统计规律,求和的时候都不需要迭代,可以一次计算出这个值,我没有那么多耐心,还是老老实实的循环
private static int[] num_letters = { 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8, 6, 6, 5, 5, 5, 7, 6, 6 }; private static int numLetters(int N) { int result = 0, hun = N / 100 % 10, ten = N / 10 % 10, sin = N % 10; if (hun > 0) { result += num_letters[hun - 1] + 7; // 等于个位数hundred if (ten > 0 || sin > 0) result += 3;// 如果不是整百需加上'and' } if (ten == 1) { result += num_letters[9 + sin]; } else { if (ten > 1) result += num_letters[17 + ten]; if (sin > 0) result += num_letters[sin - 1]; } return result; } private static int sumLetters(int N) { int result = 0; if (N == 1000) { result += 11; N--; } for (int i = 1; i <= N; i++) { result += numLetters(i); } return result; }