# 两个长数字相加

## 2.编程实现

package com.sino.daily.code_2019_6_29;

import org.apache.commons.lang3.StringUtils;

/**
* create by 2019-06-29 19:03
*
* @author caogu
*/
public class Main {
public static void main(String[] args) {

String num1 = new String("1111111122323233333333388");
String num2 = new String("1111111122323233333333");

Main m = new Main();
System.out.println(m.sum(num1, num2));
}

private String sum(String num1, String num2) {
String maxNum = num1.length() > num2.length() ? num1 : num2;
String minNum = num1.length() < num2.length() ? num1 : num2;

//前面用0补齐
minNum = StringUtils.repeat("0", maxNum.length() - minNum.length()) + minNum;

System.out.println(maxNum);
System.out.println(minNum);
System.out.println(StringUtils.repeat("-", maxNum.length()) + "  +");

//按位相加，向上进位
StringBuilder sum = new StringBuilder();
int carryBit = 0;
for (int i = maxNum.length() - 1; i >= 0; i--) {
int bitNum1 = Integer.parseInt(String.valueOf(maxNum.charAt(i)));
int bitNum2 = Integer.parseInt(String.valueOf(minNum.charAt(i)));

int bitSum = bitNum1 + bitNum2 + carryBit;
sum.append(bitSum % 10);

carryBit = bitSum / 10;
}

//处理最高位
if (carryBit != 0) {
sum.append(carryBit);
}

// 字符串反转输出
return sum.reverse().toString();
}
}