[Project Euler] Problem 17

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.

 

我们先来看看数字有什么规律吧

0:null           10:ten            20:twenty            ......           100:one hundred

1:one          11:eleven        21:twenty-one      ......           101:one hundred and one

2:two          12:twelve        22:twenty-two      ......           102:one hundred and two

.........

 

1000 one thousand

 

可以看出当十位是1时,要单独考虑。

当十位数不是1时,是在十位数的基础上加上各位数的长度

当有百位数时,百位由百位上的数加上hundred and

为整百时,会少一个and

 

 

所以编程如下

#include < iostream >
using namespace std;

int main(){
int letters = 0 ;
const int Unit[ 10 ] = { 0 , 3 , 3 , 5 , 4 , 4 , 3 , 5 , 5 , 4 };
const int Tens[ 10 ] = { 0 , 0 , 6 , 6 , 5 , 5 , 5 , 7 , 6 , 6 };
const int Tensone[ 10 ] = { 3 , 6 , 6 , 8 , 8 , 7 , 7 , 9 , 8 , 8 };
for ( int i = 1 ;i < 1000 ;i ++ ){
if (i / 10 % 10 == 1 ){
letters
= letters + Tensone[i % 10 ];
}
else {
letters
= letters + Unit[i % 10 ];
letters
+= Tens[i / 10 % 10 ];
}
if (i / 100 > 0 ){
if (i % 100 == 0 ){
letters
+= Unit[i / 100 ] + 7 ;
}
else {
letters
+= Unit[i / 100 ] + 10 ;
}
}
}
letters
+= 11 ;
cout
<< letters << endl;
return 0 ;
}

 

这道题就是要考虑完所有特殊情况

 

你可能感兴趣的:(project)