超大型数据无法存储在系统内存中,不过可以使用BigInteger和BigDecimal进行数据的存储和运算。不过如果遇到数据位数更大,超过千万位时该方法也同样不能满足要求了,只有使用最基本的方法进行处理。
package com.javaexam.test;
import java.util.Scanner;
public class BigInteger {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String a = in.next();
String b = in.next();
int[] aa = new int[a.length()];
int[] bb = new int[b.length()];
for(int i = a.length();i>=1;i--){
aa[a.length()-i] = Integer.valueOf(a.substring(i-1,i));
}
for(int j = b.length();j>=1;j--){
bb[b.length()-j] = Integer.valueOf(b.substring(j-1,j));
}
if(a.length()<b.length()){
String result1 = "-"+minus(bb,aa);
System.out.println(result1);
}
if(a.length()==b.length()){
int comp = compare(a, b);
if(comp<0){
String result_1 = "-"+minusMid(bb,aa);
System.out.println(result_1);
}
if(comp==0){
System.out.println("0");
}
if(comp>0){
String result_2 = minusMid(aa,bb);
System.out.println(result_2);
}
}
if(a.length()>b.length()){
String result2 = minus(aa,bb);
System.out.println(result2);
}
}
}
public static int compare(String a ,String b){
int compare_result = a.compareTo(b);
return compare_result;
}
public static String minusMid(int[] x,int[] y){
String result = "";
int[] xy = new int[x.length];
for(int i = 0;i<x.length;i++){
if(i==0){
xy[i] = x[i]+10-y[i];
}else if(i==x.length-1){
xy[i] = x[i]-1-y[i];
}else{
xy[i] = x[i]+10-1-y[i];
}
}
for(int m=0;m<x.length-1;m++){
if(xy[m]>=10){
xy[m] -= 10;
xy[m+1] += 1;
}
String num = Integer.toString(xy[m]);
result = num+result;
}
// if(xy[x.length-1]!=0){
// result = Integer.toString(xy[x.length-1]).replaceFirst("^0*", "")+result;
// }
return result.replaceFirst("^0*", "");
}
public static String minus(int[] x,int[] y){
String result = "";
int[] xy = new int[x.length];
for(int i=0;i<y.length;i++){
if(i==0){
xy[i] = x[i]+10-y[i];
}else{
xy[i] = x[i]+10-1-y[i];
}
}
for(int j=y.length;j<x.length;j++){
if(j==x.length-1){
xy[j] = x[j] -1;
}else{
xy[j] = x[j]+10-1;
}
}
for(int m=0;m<x.length;m++){
if(xy[m]>=10){
xy[m] -= 10;
xy[m+1] += 1;
}
String num = Integer.toString(xy[m]);
result = num+result;
}
return result.replaceFirst("^0*", "");
}
}