模拟手算即可。每一位的计算都应考虑进位。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Scanner;
class BigInteger {
ArrayList<Integer> data = new ArrayList<>();
private BigInteger(){
}
public BigInteger(int initValue){
this(initValue + "");
}
public BigInteger(long initValue){
this(initValue + "");
}
public BigInteger(String initValue){
for(int i = initValue.length() - 1; i >= 0; i--){
char ch = initValue.charAt(i);
if(ch > '9' || ch < '0'){
ch = '0';
}
data.add(ch - '0');
}
}
/** 加法 */
public BigInteger add(BigInteger target){
BigInteger result = new BigInteger();
int ins = 0;
int i = 0;
int j = 0;
int m = this.data.size();
int n = target.data.size();
while(i < m || j < n){
int a = i < m ? this.data.get(i) : 0;
int b = i < n ? target.data.get(j) : 0;
int d = a + b + ins;
if(d >= 10){
ins = 1;
result.data.add(d - 10);
}else{
ins = 0;
result.data.add(d);
}
i++;
j++;
}
if(ins != 0){
result.data.add(ins);
}
return result;
}
/** 乘法 */
public BigInteger multiply(BigInteger target){
BigInteger result = new BigInteger();
int ins = 0;
int m = this.data.size();
int n = target.data.size();
int l = Math.max(m, n);
for(int i = 0; i < 2*l; i++){
int sum = ins;
for(int j = 0; j <= i; j++){
int a = j < m ? this.data.get(j) : 0;
int b = (i - j) < n ? target.data.get(i - j) : 0;
sum += (a * b);
}
if(sum >= 0){
ins = sum / 10;
result.data.add(sum % 10);
}else{
ins = 0;
result.data.add(sum);
}
}
if(ins != 0){
result.data.add(ins);
}
return result;
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
for(int i = data.size() - 1; i >= 0; i--){
sb.append(data.get(i));
}
return sb.toString();
}
}
// Main.java for vijio
public class Main {
public static void main(String[] args) {
System.out.println(new BigInteger("50243572390475").add(new BigInteger("50243572390475")));
System.out.println(new BigInteger("50243572390475").multiply(new BigInteger("50243572390475")));
}
}
测试结果如下,结果是正确的: