您的位置:首页 > 其它

UVa 465 Overflow

2010-02-24 20:12 477 查看
/*
coder: ACboy
date: 2010-2-24
result: AC
description: UVa 465 Overflow
*/

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

// 把INT_MAX转换成string并返回。
string intMaxToStr()
{
string str = "";
int k = INT_MAX;
while (k != 0)
{
int temp = k % 10;
str = char(temp + '0') + str;
k /= 10;
}
return str;
}

// 比较两个(整数)字符串
int cmp(string a, string b)
{
int alen = a.size();
int blen = b.size();
if (alen != blen) return alen > blen;
else return a > b;
}

// 删除前导零。
void delLeadZero(string & a)
{
int i = 0;
while (a[i] == '0') i++;
if (i == a.size()) a = "0";
else a = a.substr(i, a.size() - i);
}

int main()
{
string input;
char op;
string a, b;
#ifndef ONLINE_JUDGE
freopen("465.txt", "r", stdin);
#endif
while (getline(cin, input))
{
cout << input << endl;
int flagMax1;
int flagMax2;
istringstream in(input);
in >> a >> op >> b;
delLeadZero(a);
delLeadZero(b);
string intMaxStr = intMaxToStr();
// 用来标记第一个数和第二个数是否为大整数。
flagMax1 = 0;
flagMax2 = 0;
if (cmp(a, intMaxStr)) flagMax1 = 1;
if (cmp(b, intMaxStr)) flagMax2 = 1;
if (flagMax1 == 1 && flagMax2 == 1)
{
cout << "first number too big" << endl;
cout << "second number too big" << endl;
cout << "result too big" << endl;
}
else if (flagMax1 == 1 && flagMax2 == 0)
{
cout << "first number too big" << endl;
if (op == '+')
cout << "result too big" << endl;
else if (op == '*' && b != "0")
cout << "result too big" << endl;
}
else if (flagMax1 == 0 && flagMax2 == 1)
{
cout << "second number too big" << endl;
if (op == '+')
cout << "result too big" << endl;
else if (op == '*' && a != "0")
cout << "result too big" << endl;
}
else
{
int i;
double a_i = 0, b_i = 0;
int alen = a.size();
int blen = b.size();

// 把(整数)字符串转换成浮点数保存在a_i, b_i中,要用
// double类型,因为a_i, b_i有可能为零。用int来存储时
// INT_MAX / a_i 有可能出现除零的错误。
for (i = 0; i < alen; i++)
{
a_i *= 10;
a_i += a[i] - '0';
}
for (i = 0; i < blen; i++)
{
b_i *= 10;
b_i += b[i] - '0';
}
if (op == '*' && (INT_MAX / a_i < b_i))
{
cout << "result too big" << endl;
}

if (op == '+' && INT_MAX - a_i < b_i)
{
cout << "result too big" << endl;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string input 存储 2010