记录一道手撕代码的面试题
大整数相加可以用BigInteger解决。(但是面试肯定不会让你用这个)
//BigInteger类解决(可用于对后续代码结果的测试)
public static void main(String[] args) {
String s1 = "11567890087657890876";
String s2 = "19133324567865654123234";
BigInteger num1 = new BigInteger(s1);
BigInteger num2 = new BigInteger(s2);
BigInteger num3 = num1.add(num2);
System.out.println(num3);
}
//一般解法:
public static void main(String[] args) {
//大整数相加
String s1 = "11567890087657890876";
String s2 = "19133324567865654123234";
char[] num1 = new StringBuffer(s1).reverse().toString().toCharArray();
char[] num2 = new StringBuffer(s2).reverse().toString().toCharArray();
StringBuilder result = new StringBuilder();
int carry = 0;
int maxIndex1 = Math.min(num1.length, num2.length);
int maxIndex2 = Math.max(num1.length, num2.length);
//处理长度一致的部分
for(int i = 0;i<maxIndex1;i++){
int temp = (num1[i]-'0')+(num2[i]-'0')+carry;//利用ASCII码的特点进行按位相加运算
result.append(temp%10);
carry = temp/10;
}
//处理多余长度部分
//没有进位直接拼接剩余部分
if(carry==0){
for(int i = maxIndex1;i<maxIndex2;i++){
if(num1.length>num2.length){
result.append(num1[i]);
}else{
result.append(num2[i]);
}
}
}else{//有进位要用剩余部分再次和进位相加
for(int i = maxIndex1;i<maxIndex2;i++){
if(num1.length>num2.length){
int temp = (num1[i]-'0')+carry;
result.append(temp%10);
carry = temp/10;
}else{
int temp = (num2[i]-'0')+carry;
result.append(temp%10);
carry = temp/10;
}
}
}
System.out.println(result.reverse().toString());
}