题目:
题解:
1.逐位相加
按照传统加减法模式,从最后一位开始,逐位相加,逢十进一,传统方式从右往左相加,可以将数字翻转,变成从左往右按照数组遍历顺序相加,最后再将结果翻转。
java
public String getSum(String str1, String str2) {
// 翻转
List<Integer> list1 = revers(str1);
List<Integer> list2 = revers(str2);
int len1 = list1.size();
int len2 = list2.size();
int carryBit = 0;
StringBuilder sb = new StringBuilder();
int length = len1 > len2 ? len1 : len2;
for (int i = 0; i < length; i++) {
// 如果超出则取0
int value1 = getValue(list1, i);
int value2 = getValue(list2, i);
int sum = value1 + value2 + carryBit;
if (sum < 10) {
sb.append(sum);
carryBit = 0;
} else {
sb.append(sum % 10);
carryBit = sum/10;
}
}
// 如果最后还有进位,需要添加进位
if (carryBit != 0) {
sb.append(carryBit);
}
// 翻转结果
sb.reverse();
return sb.toString();
}
private int getValue(List<Integer> list, int index) {
if (index >= list.size()) {
return 0;
}
return list.get(index);
}
private List<Integer> revers(String str) {
char[] chars = str.toCharArray();
List<Integer> list = new ArrayList<>(chars.length);
for (int i = chars.length - 1; i >= 0; i--) {
list.add(chars[i] - '0');
}
return list;
}
时间复杂度:O(n+m)
2.利用大整形类型BigInteger实现
java
public String getSum(String str1, String str2) {
BigInteger bigInteger1 = new BigInteger(str1);
BigInteger bigInteger2 = new BigInteger(str2);
bigInteger1 = bigInteger1.add(bigInteger2);
return bigInteger1.toString();
}