# 大数问题

## 大数加法

String BigNumberAdd(String num1, String num2){
if(num1==null||num1.length()==0) return num2;
if(num2==null||num2.length()==0) return num1;
int len = Math.max(num1.length(), num2.length()) + 1;

char[] charNum1 = new char[len];
char[] charNum2 = new char[len];
Arrays.fill(charNum1, '0');
Arrays.fill(charNum2, '0');
for(int i=num1.length()-1,j=len-1;i>=0;i--,j--){
charNum1[j] = num1.charAt(i);
}
for(int i=num2.length()-1,j=len-1;i>=0;i--,j--){
charNum2[j] = num2.charAt(i);
}

//进位的问题
int carry = 0;
for(int j=len-1;j>=0;j--){
int curSum = (charNum1[j]-'0') + (charNum2[j]-'0') + carry;
if(curSum>9){
carry = 1;
curSum-=10;
}
charNum1[j] = (char)(curSum + '0');
}

StringBuilder sb = new StringBuilder();
int notZero = 0;
while(notZero<len-1 &&charNum1[notZero]=='0')
notZero++;
while(notZero<len)
sb.append(charNum1[notZero++]);

return sb.toString();
}


## 大数减法

String BigNumberSubstract(String num1, String num2){
if(num1==null||num1.length()==0) return '-'+num2;
if(num2==null||num2.length()==0) return num1;

int len = Math.max(num1.length(), num2.length());
char[] charNum1 = new char[len];
char[] charNum2 = new char[len];
Arrays.fill(charNum1, '0');
Arrays.fill(charNum2, '0');

int sign = 0;
if(num1.compareTo(num2)<0){
//被减数小于减数时，则最后结果一定为负
String temp = num1;
num1 = num2;
num2 = temp;
sign = -1;//符号位
}

for(int i=num1.length()-1,j=len-1;i>=0;i--,j--){
charNum1[j] = num1.charAt(i);
}
for(int i=num2.length()-1,j=len-1;i>=0;i--,j--){
charNum2[j] = num2.charAt(i);
}

int borrow = 0;
for(int j=len-1;j>=0;j--){
int curSub = (charNum1[j]-'0') - (charNum2[j]-'0') - borrow;
if(curSub<0){
borrow = 1;
curSub +=10;
}
else borrow = 0;
charNum1[j] = (char)(curSub + '0');
}

StringBuilder sb = new StringBuilder();
int notZero = 0;
//从高位往低位找第一个非零的数字（最后一位数字不在范围内，全为0则输出最后一个0）
while(notZero<len-1 && charNum1[notZero]=='0')
notZero++;
while(notZero<len)
sb.append(charNum1[notZero++]);
if(sign == -1) sb.insert(0, '-');

return sb.toString();
}