需要注意两点:1、前导0要删除;2、a或者b溢出,c也不一定溢出,a或b为0的话结果为0。
以下是我的代码:
#include <iostream>
#include <sstream>
#include <string>
#include <cstdio>
using namespace std;
typedef long long int64;
const string kInf = "2147483647";
int cmp ( const string &a, const string &b )
{
if ( a.size() > b.size() )
return 1;
else if ( a.size() < b.size() )
return -1;
else
{
for ( int i = 0; i < a.size(); i++ )
if ( a[i] > b[i] )
return 1;
else if ( a[i] < b[i] )
return -1;
return 0;
}
}
int main ()
{
#ifndef ONLINE_JUDGE
freopen ( "data.in", "r", stdin );
#endif
string a, t, b;
while ( cin >> a >> t >> b )
{
cout << a << " " << t << " " << b << endl;
while ( a.size() > 1 && a[0] == '0' )
a.erase ( 0, 1 );
//cout << a << endl;
while ( b.size() > 1 && b[0] == '0' )
b.erase ( 0, 1 );
//cout << b << endl;
bool over = false;
if ( cmp ( a, kInf ) > 0 )
{
printf ( "first number too big\n" );
over = true;
}
if ( cmp ( b, kInf ) > 0 )
{
printf ( "second number too big\n" );
over = true;
}
if ( over )
{
if ( t == "+" || ( t == "*" && a != "0" && b != "0" ) )
printf ( "result too big\n" );
continue;
}
int64 aa, bb, cc;
istringstream ( a ) >> aa;
istringstream ( b ) >> bb;
if ( t == "+" )
cc = aa + bb;
else
cc = aa * bb;
if ( cc > 0x7fffffff )
printf ( "result too big\n" );
}
return 0;
}
posted on 2011-09-08 10:42
lee1r 阅读(563)
评论(1) 编辑 收藏 引用 所属分类:
题目分类:数学/数论