还不支持负数加(实则减)的情况。也不支持非数字字符的检测。
class Solution {
public String add(String addend1, String addend2) {
StringBuilder buf = new StringBuilder();
for ( int i1 = addend1.length() - 1, i2 = addend2.length() - 1, carry = 0;
i1 >= 0 || i2 >= 0 || carry != 0;i1--, i2-- ) {
int digit1 = i1 < 0 ? 0 : addend1.charAt(i1) - '0';
int digit2 = i2 < 0 ? 0 : addend2.charAt(i2) - '0';
int digit = digit1 + digit2 + carry;
if (digit > 9) {
carry = 1;
digit -= 10;
} else {
carry = 0;
}
buf.append(digit);
}
return buf.reverse().toString();
}
}