[Problem 17]欧拉

这一题乍看上去比较困难。稍作思考就会发现其算法非常明显。具体思路下面的代码的comment中写得很清楚了。(第一遍实现后发现post到欧拉上说答案不对;后来发现是11X, 21X和12X,24X的计算方法不同这点没有考虑到。更正算法,终于得到正确答案)

View Code
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    
// 1 - 1000 word number calculation.
    
//
    unsigned long sum = 0;

    
// 1-19. Rule: as every word in this range is special so we have to write and calculate every word.           
    unsigned long arrA[] = { 
        
0,
        
3/*one*/
        
3/*two*/
        
5/*three*/
        
4/*four*/,
        
4/*five*/,
        
3/*six*/,
        
5/*seven*/,
        
5/*eight*/,
        
4/*nine*/,
        
3/*ten*/,
        
6/*eleven*/,
        
6/*twelve*/,
        
8/*thirteen*/,
        
8/*fourteen*/,
        
7/*fifteen*/,
        
7/*sixteen*/,
        
9/*seventeen*/,
        
8/*eighteen*/,
        
8/*nineteen*/
    };

    
for(int i = 1; i < 20; i++)
    {
        sum 
+= arrA[i];
    }

    
// 20-99. Rule: for example, 24-- twenty four. Letters it uses == number of (twenty) arrB[] + number of (four) arrA[].
    unsigned long arrB[] = { 
        
0,
        
3/*"ten"*/
        
6/*"twenty"*/
        
6/*"thirty"*/
        
5/*"forty"*/,  
        
5/*"fifty"*/
        
5/*"sixty"*/
        
7/*"seventy"*/
        
6/*"eighty"*/
        
6/*"ninety"*/};
    
int geWei;
    
int shiWei;
    
for (int i = 20; i <= 99; i++ )
    {
        geWei 
= i % 10;
        
if(geWei > 0)
            sum 
+= arrA[geWei];

        shiWei 
= i / 10;
        
if(shiWei > 0)
            sum 
+= arrB[shiWei];
    }

    
// 100-999. The rule is: for example, 112 == (one) (hundred and) (twelve); 123 == (one) (hundred and) (twenty) (three). You can
    
// see clearly where to retrieve each part's letter number.
    unsigned long nNumA = 7;//"hundred";
    unsigned long nNumB = 10// "hundred and"
    int baiWei = 0// 123's baiWei is 1.
    int yushu = 0// 123's yushu is 23.
    bool bNotSingle = false// 100 is single while 101 is notSingle.
    for (int i = 100; i <= 999; i++)
    {
        bNotSingle 
= true;

        yushu 
= i % 100;
        
if(yushu > 0 && yushu < 20)
            sum 
+= arrA[yushu];
        
else if(yushu >= 20)
        {
            geWei 
= yushu % 10;
            
if(geWei > 0)
                sum 
+= arrA[geWei];

            shiWei 
= yushu / 10;
            
if(shiWei > 0)
                sum 
+= arrB[shiWei];
        }
        
else
            bNotSingle 
= false;        

        baiWei 
= i / 100;
        
if (bNotSingle)
            sum 
= sum + nNumB + arrA[baiWei];
        
else
            sum 
= sum + nNumA + arrA[baiWei];        

    }

    
// 1000
    sum += 11// "one thousand".

    cout 
<< "sum:" << endl;
    cout 
<< sum << endl;           


    
return 0;
}

 

 

posted @ 2011-04-13 18:09  能巴  阅读(178)  评论(0)    收藏  举报