问题描述如下:
“从1到5的单词为:one,two,three,four,five,一共有3+3+5+4+5=19个字母,那么从1到1000(one thousand)的单词一共有多少个字母?
note:不计空格及连字符。例如,342(three hundred and forty-two)有23个字母和115(one hundred and fifteen)有20个字母,在英国人的使用习惯中,‘and’在写数字中是必不可少的。”
代码实现如下:
/**
* 字母总数
* @return
*/
private static int getSum() {
int sum = 0;
for (int i = 1; i <= 1000; i++) {
System.out.println(i + ":" + getCount(i));
sum += getCount(i);
}
return sum;
}
/**
* 获得某个数字的字母长度,最大数字不操作1000
*
* @param number
* @return
*/
private static int getCount(int number) {
int[] singleWord = { 4, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7,
9, 8, 8 };
int[] tensWord = { 0, 0, 6, 6, 5, 5, 5, 7, 6, 6 };// 0 10 20 30...90
int hundred = 7;
int thousand = 8;
int count = 0;
if (number == 1000) {
return 3 + thousand;
}
if (number / 100 > 0) {
count += singleWord[number / 100] + hundred;// 百位
if (number % 100 > 0) {
count += 3;// and
}
}
if (number % 100 >= 20) {// 大于20的
count += tensWord[number / 10 % 10];// 十位
if (number % 10 > 0) {
count += singleWord[number % 10];// 个位
}
} else if (number % 100 > 0) {// 小于20的
count += singleWord[number % 100];
}
return count;
}
结果为:21124
请不吝赐教。
@anthor ClumsyBirdZ