题目:给你一个计算式(2个操作数,一个运算符),问操作数和结果是否溢出。
分析:模拟。转换成大数运算,然后分别把每个数字转化成整型,看是否相同即可。
注意:<cstring>库中没有strrev;输出的原数字的前导0不要丢掉。
#include <iostream>
#include <cstdlib>
#include <string.h>
#include <cstdio>
using namespace std;
char a[10000],b[10000],c[10000],d[10000];
int a_buf[10000],b_buf[10000],c_buf[10000];
int over_flow( char* s )
{
//去除前导0
char buf[10000];
int len = strlen(s),now = 0;
while ( now+1 < len && s[now] == '0' )
now ++;
strcpy( buf, &s[now] );
int value = 0;
for ( int i = 0 ; buf[i] ; ++ i ) {
value *= 10;
value += buf[i]-'0';
}
char A[10000],B[10000];
int count = 0;
while ( !count || value ) {
A[count ++] = value%10 + '0';
value /= 10;
}
int times = 0;
while ( count )
B[times ++] = A[-- count];
B[times] = 0;
return strcmp( buf, B );
}
void plu( char* d, char* a, char* b )
{
memset( a_buf, 0, sizeof( a_buf ) );
memset( b_buf, 0, sizeof( b_buf ) );
memset( c_buf, 0, sizeof( c_buf ) );
int l_a = strlen(a),l_b = strlen(b);
int len = max(l_a, l_b )+1;
for ( int i = 0 ; i < l_a ; ++ i )
a_buf[i] = a[l_a-1-i]-'0';
for ( int i = 0 ; i < l_b ; ++ i )
b_buf[i] = b[l_b-1-i]-'0';
for ( int i = 0 ; i < len ; ++ i ) {
c_buf[i] += a_buf[i] + b_buf[i];
if ( c_buf[i] > 9 ) {
c_buf[i+1] ++;
c_buf[i] -= 10;
}
}
while ( len > 0 && !c_buf[len] ) -- len;
for ( int i = 0 ; i <= len ; ++ i )
d[i] = c_buf[len-i]+'0';
d[len+1] = 0;
}
void mul( char* d, char* a, char* b )
{
memset( a_buf, 0, sizeof( a_buf ) );
memset( b_buf, 0, sizeof( b_buf ) );
memset( c_buf, 0, sizeof( c_buf ) );
int l_a = strlen(a),l_b = strlen(b);
int len = l_a*l_b+1;
for ( int i = 0 ; i < l_a ; ++ i )
a_buf[i] = a[l_a-1-i]-'0';
for ( int i = 0 ; i < l_b ; ++ i )
b_buf[i] = b[l_b-1-i]-'0';
for ( int i = 0 ; i < l_a ; ++ i )
for ( int j = 0 ; j < l_b ; ++ j )
c_buf[i+j] += a_buf[i] * b_buf[j];
for ( int i = 0 ; i < len ; ++ i )
if ( c_buf[i] > 9 ) {
c_buf[i+1] += c_buf[i]/10;
c_buf[i] %= 10;
}
while ( len > 0 && !c_buf[len] ) -- len;
for ( int i = 0 ; i <= len ; ++ i )
d[i] = c_buf[len-i]+'0';
d[len+1] = 0;
}
int main()
{
while ( cin >> a >> c >> b ) {
cout << a << " " << c << " " << b << endl;
if ( over_flow(a) )
cout << "first number too big" << endl;
if ( over_flow(b) )
cout << "second number too big" << endl;
if ( c[0] == '+' ) plu( d, a, b );
if ( c[0] == '*' ) mul( d, a, b );
if ( over_flow(d) )
cout << "result too big" << endl;
}
return 0;
}