//给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
//
//
//
// 提示:
//
//
// num1 和num2 的长度都小于 5100
// num1 和num2 都只包含数字 0-9
// num1 和num2 都不包含任何前导零
// 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式
//
// Related Topics 字符串
// 👍 313 👎 0
class Solution { public String addStrings2(String num1, String num2) { if ("0".equals(num1)) { return num2; } if ("0".equals(num2)) { return num1; } int carry = 0; int num1Index = num1.length() - 1; int num2Index = num2.length() - 1; StringBuilder sb = new StringBuilder(); while (carry > 0 || num1Index >= 0 || num2Index >= 0) { char ch1 = num1Index >= 0 ? num1.charAt(num1Index) : '0'; char ch2 = num2Index >= 0 ? num2.charAt(num2Index) : '0'; // 计算 int sum = ch1 + ch2 - '0' - '0' + carry; sb.append(sum % 10); carry = sum / 10; num1Index--; num2Index--; } return sb.reverse().toString(); } }