题目地址:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=97&page=show_problem&problem=406
用java的大数类处理,提交WA,未找到原因,好蛋疼。。。
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner cin = new Scanner(System.in);
Integer maxInt = Integer.MAX_VALUE;
BigInteger a = null;
BigInteger b = null;
BigInteger res = null;
String op = null;
BigInteger max = new BigInteger(maxInt.toString());
while (cin.hasNext()) {
a = new BigInteger(cin.next());
op = cin.next();
b = new BigInteger(cin.next());
System.out.println(a + " " + op + " " + b);
if (a.compareTo(max) > 0)
System.out.println("first number too big");
if (b.compareTo(max) > 0)
System.out.println("second number too big");
if (op.equals("+") && ((a.add(b)).compareTo(max) > 0))
System.out.println("result too big");
if (op.equals("*") && ((a.multiply(b)).compareTo(max) > 0))
System.out.println("result too big");
}
}
}
C++代码AC了,偷了个懒没有用字符串处理,而是用double存储,double有15-16位精度,对于最大不超过10位的int够用了,即使整数数字很大,超过了double的精度表示范围,但是数字的数量级也足以溢出了。
#include<cstdio>
#include<cstdlib>
#include<cstring>
const int MAX=1000;
int main()
{
char a[MAX];
char b[MAX];
char op;
const int maxInt=0x7fffffff;
double aNum;
double bNum;
while(scanf("%s %c %s",a,&op,b)!=EOF)
{
printf("%s %c %s\n",a,op,b);
aNum=atof(a);
bNum=atof(b);
if(aNum>maxInt)
printf("first number too big\n");
if(bNum>maxInt)
printf("second number too big\n");
if(op=='+')
{
if(aNum+bNum > maxInt)
printf("result too big\n");
}
else
{
if(aNum*bNum>maxInt)
printf("result too big\n");
}
}
return 0;
}