思路是模拟从低位到高位的按位相加,需要考虑进位
public String addStrings(String num1, String num2) {
int bitLen1 = num1.length() - 1, bitLen2 = num2.length() - 1;
StringBuilder stringBuilder = new StringBuilder();
int carry = 0;
while (bitLen1 >= 0 || bitLen2 >= 0 && carry > 0) {
int bit1 = bitLen1 >= 0 ? num1.charAt(bitLen1) - '0' : 0;
int bit2 = bitLen2 >= 0 ? num2.charAt(bitLen2) - '0' : 0;
int sum = bit1 + bit2 + carry;
carry = sum / 10;
stringBuilder.append(sum % 10);
bitLen1--;
bitLen2--;
}
stringBuilder.reverse();
return stringBuilder.toString();
}
标签:num1,int,stringBuilder,相加,bitLen1,bitLen2,力扣,415,carry
From: https://www.cnblogs.com/yaocy/p/18327421