此题目的意思是:形如下面的两个字符串阶乘,判断哪个更大。

12!!!! 和 3!!!!!。前者有4个阶乘号,后者有5个。

利用的原理就是:越大的数的同阶阶乘越大。也就是阶乘的单调性。所以可以直接去掉相同个数的阶乘号后再作比较。

没有写大整数类,所以请不要用剩余两个!!以上的数测试,会溢出。

下面是主要函数的代码:

#include <iostream>
#include
<string>
#include
<algorithm>

using namespace std;

long long factorial( string&
str )
{
    
int excl = count( str.begin(), str.end(), '!'
);
    
string temp = str.substr( 0, str.size() -
excl );
    
long long number =
atoi( temp.c_str() );
    
    
for ( int i = 0 ; i < excl ; i++
)
     {
        
long long t = 1
;
        
for( long long k = 1 ; k <= number ; k++
)
         {
             t
*=
k;
         }
         number
=
t;
     }
     cout
<<"The value of longer number cut off is : "<<number<<
endl;
     cout
<<"----------------"<<
endl;
    
return
number;
}

//return 1 if a > b. else return -1

int compare(string& a, string& b)
{
    
int excl_a = count( a.begin(), a.end(), '!'
);
    
int excl_b = count( b.begin(), b.end(), '!'
);

    
int excl =
min( excl_a, excl_b );

    
//cut off exclamation

    string aa = a.substr( 0, a.size() - excl );
     cout
<<"The first number cut off is : "<<aa<<
endl;
    
string bb = b.substr( 0, b.size() -
excl );
     cout
<<"The second number cut off is : "<<bb<<
endl;
     cout
<<"-------------"<<
endl;

    
//without exclamation

    if ( aa.find( '!', 0 ) != string::npos ) //exclamation in aa
     {
        
long long first =
factorial( aa );
        
long long second =
atoi( bb.c_str() );
        
if ( first >
second )
            
return 1
;
        
else

            
return -1;
     }
    
else //no exclamation in aa

     {
        
long long first =
factorial( bb );
        
long long second =
atoi( aa.c_str() );
        
if ( first >
second )
            
return -1
;
        
else

            
return 1;
     }
}

下面是测试的主函数:

int main()
{
    
string a( "12!!!!"
);
     cout
<<"The first number is : "<<a<<
endl;
    
string b( "3!!!!!"
);
     cout
<<"The second number is : "<<b<<
endl;
     cout
<<"------------"<<
endl;

     cout
<<a<<" "<<( ( compare( a, b ) > 0 ) ? ">" : "<" )<<" "<<b<<
endl;

     cout
<<endl<<
endl;

    
string c( "6!!!"
);
     cout
<<"The first number is : "<<c<<
endl;
    
string d( "500!!"
);
     cout
<<"The second number is : "<<d<<
endl;
     cout
<<"------------"<<
endl;

     cout
<<c<<" "<<( ( compare( c, d ) > 0 ) ? ">" : "<" )<<" "<<d<<
endl;
}



通过 Wiz 发布


posted on 2011-05-11 22:56  微型葡萄  阅读(579)  评论(0编辑  收藏  举报