题解:用正常做法,将两个数提取,将他们的结果也提取,判断是否大于int,,注意 0 * 这个陷阱。巧妙的方法有将两个数所在的字符串用atof()函数转成double类型,和int比大小。。。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const char c[10] = {'2', '1', '4', '7', '4', '8', '3', '6', '4', '7'};
int k, flag;
int judge(string s) {
int len = s.size(), i;
if (len > 10) {
for (i = 0; i < len; i++)
if (s[i] != '0' && (len - i - 1) >= 10)
return 1;
}
else if (len == 10 )
for (i = 0; i < len; i++) {
if (s[i] < c[i])
break;
if (s[i] > c[i])
return 1;
}
return 0;
}
int result(string s1, string s2) {
int ans[500] = {0}, a[500] = {0}, b[500] = {0};
string anss = "";
int i, j, q;
int len1 = s1.size();
int len2 = s2.size();
if (flag == 1) {
for (i = 0; i < len1; i++)
a[i] = s1[len1 - 1 - i] - '0';
for (i = 0; i < len2; i++)
b[i] = s2[len2 - 1 - i] - '0';
int lenx = len1 > len2 ? len1 : len2;
for (i = 0; i < lenx; i++) {
ans[i] = a[i] + b[i] + ans[i];
ans[i + 1] = ans[i] / 10;
ans[i] = ans[i] % 10;
}
if (ans[lenx])
lenx++;
for (j = lenx - 1; j >= 0; j--)
anss += ans[j] + '0';
// cout << anss << endl;
int a = judge(anss);
if (a == 1)
return 1;
else
return 0;
}
if (flag == 2) {
int ans[500] = {0};
for (i = len1 - 1; i >= 0; i--)
for (j = len2 - 1, q = len1 - 1 - i; j >= 0; j--)
ans[q++] += (s1[i] - '0') * (s2[j] - '0');
for (i = 0; i < 500; i++) {
ans[i + 1] += ans[i] / 10;
ans[i] %= 10;
}
for (i = 499; i >=0; i--)
if (ans[i] != 0)
break;
if (i == -1)
return 0;
else
for (q = i; q >= 0; q--)
anss += ans[q] + '0';
int a = judge(anss);
if (a == 1)
return 1;
else
return 0;
}
}
int main(){
string str, str1, str2;
while(getline(cin, str)) {
k = 0;
int length = str.size();
str1 = "";
str2 = "";
flag = 0;
for (int i = 0; i < length; i++)
if(str[i] >= '0' && str[i] <= '9' && flag == 0)
str1 += str[i];
else if (str[i] == '+')
flag = 1;
else if (str[i] == '*')
flag = 2;
else if (str[i] >= '0' && str[i] <= '9' && flag != 0)
str2 += str[i];
cout << str << endl;
int k1 = judge(str1);
int k2 = judge(str2);
if (k1 == 1)
cout << "first number too big" << endl;
if (k2 == 1)
cout << "second number too big" << endl;
if (flag == 2) { //判断0 * ? 结果不会大于int
int i, j;
if (k1 == 1) {
int len2 = str2.size();
for (i = 0; i < len2; i++)
if (str2[i] != '0')
break;
if (i == len2)
continue;
}
else if (k2 == 1) {
int len1 = str1.size();
for (j = 0; j < len1; j++)
if (str1[j] != '0')
break;
if (j == len1)
continue;
}
}
if (k1 == 1 || k2 == 1)
cout << "result too big" << endl;
else
if (result(str1, str2) == 1)
cout << "result too big" << endl;
}
return 0;
}