全部博文(68)
分类: C/C++
2012-01-25 17:05:32
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.
答案:21124
#include
const int singleWord[20] =
{ 4, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8 };
const int tensPlaceWord[10] = { 0, 0, 6, 6, 5, 5, 5, 7, 6, 6 };
const int hunWord = 7;
const int thouWord = 11;
int countLetters (int num)
{
int count = 0;
if (num == 1000) {
return thouWord;
}
if (num / 100 > 0) {
count += singleWord[num / 100] + hunWord;
if (num % 100 > 0) {
count += 3;
}
}
if (num % 100 >= 20) {
// sb.append(tensPlace[num / 10 % 10]);
count += tensPlaceWord[num / 10 % 10];
if (num % 10 > 0) {
// sb.append(" " + single[num % 10]);
count += singleWord[num % 10];
}
} else if (num % 100 > 0) {
// sb.append(single[num % 100]);
count += singleWord[num % 100];
}
return count;
}
int main(void)
{
int result=0;
for(int i=1;i<=1000;i++)
{
result+=countLetters(i);
}
printf("The result is %d\n", result);
return 0;
}