转载声明:原文转自http://www.cnblogs.com/xiezie/p/5501901.html
JAVA解题:
import java.util.*; import java.io.*;
import java.math.BigInteger; public class Main{ public static void main(String[] arg){
Scanner scan = new Scanner(new BufferedInputStream(System.in));
int n = scan.nextInt();
int l = n;
while(n--!=0){
BigInteger integer = new BigInteger(scan.next());
BigInteger integer2 = new BigInteger(scan.next());
System.out.println("Case " + (l-n+1) + ":");
System.out.println(integer + " + " + integer2 + " = " +integer.add(integer2));
if(n!=1){
System.out.println();
}
}
scan.close();
}
}
使用自定义大数处理类MBigInteger实现:
主要思路是将输入的数字作为字符串传入自定义类中,处理每个符号的计算。
实现中只处理的正整数的情况。
沿着这个思路 结合正则表达式 并完善各种BUG,可以实现百亿计算器。
以下是实现代码:
import java.util.*; import java.io.*; public class Main{ public static void main(String[] arg){
Main m = new Main();
Scanner scan = new Scanner(new BufferedInputStream(System.in));
int n = scan.nextInt();
int l = n;
while(n--!=0){
MBigInteger integer = m.new MBigInteger(scan.next());
MBigInteger integer2 = m.new MBigInteger(scan.next());
System.out.println("Case " + (l-n) + ":");
System.out.println(integer + " + " + integer2 + " = " + integer.add(integer2));
if(n!=0){
System.out.println();
}
}
scan.close();
} class MBigInteger{ private MBigInteger(){}; private String s; public MBigInteger(String s){
this.setS(s);
} public MBigInteger add(MBigInteger integer){//只处理正整数
char[] ch1 = getS().toCharArray();
char[] ch2 = integer.getS().toCharArray();
int len = ch1.length;
int len2 = ch2.length;
int n = len;
char[] resultChars;
if(len<len2){
n = len2;
}
resultChars = new char[ n ];
boolean overTen = false;
int ans;
while(len!=0&&len2!= 0){
int o = 0;
if(overTen){
o++;
}
ans = getIntValueAt(ch1, len-1) + getIntValueAt(ch2, len2-1) + o;
if(ans > 9){
overTen = true;
}else{
overTen = false;
}
resultChars[--n] = (char) (ans%10 + '0');
len -- ;
len2 -- ;
}
while(len--!=0){
int o = 0;
if(overTen){
o++;
}
ans = getIntValueAt(ch1, len) + o;
if(ans > 9){
overTen = true;
}else{
overTen = false;
}
resultChars[--n] = (char) (ans%10 + '0');
}
while(len2--!=0){
int o = 0 ;
if(overTen){
o++;
}
ans = getIntValueAt(ch2, len2) + o;
if(ans > 9){
overTen = true;
}else{
overTen = false;
}
resultChars[--n] = (char) (ans%10 + '0');
}
if(overTen){
setS("1".concat(String.valueOf(resultChars)));
}else{
setS(String.valueOf(resultChars));
}
return this;
} @Override
public String toString() {
return this.getS();
} public String getS() {
return s;
} public void setS(String s) {
this.s = s;
} public int getIntValueAt(char[] c,int i){
return c[i]-'0';
}
} }