需要改进的地方是求carry
应该用
int value = (x1 + x2 + carry) % 10;
carry = (x1 + x2 + carry) / 10;
class Solution {
public String addStrings(String num1, String num2) {
// Assuming num1 is longer.
if (num1.length() < num2.length()) {
Solution s = new Solution();
return s.addStrings(num2, num1);
}
StringBuilder sb = new StringBuilder();
int l1 = num1.length(), l2 = num2.length();
int carry = 0;
for (int i = 0; i < l1; i++) {
int v1 = num1.charAt(l1 - 1 - i) - '0';
int v2 = i >= l2 ? 0: num2.charAt(l2 - 1 - i) - '0';
int sum = v1 + v2 + carry;
if (sum >= 10) {
carry = 1;
sum -=10;
} else {
carry = 0;
}
sb.append((char)('0' + sum));
}
if (carry != 0) {
sb.append('1');
}
return sb.reverse().toString();
}
}
No comments:
Post a Comment