My code:
public class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int carry = 0;
int i = num1.length() - 1;
int j = num2.length() - 1;
while (i >= 0 || j >= 0) {
if (i < 0) {
int number = num2.charAt(j) - '0';
int sum = number + carry;
carry = sum / 10;
sb.append(sum % 10);
j--;
}
else if (j < 0) {
int number = num1.charAt(i) - '0';
int sum = number + carry;
carry = sum / 10;
sb.append(sum % 10);
i--;
}
else {
int number1 = num1.charAt(i) - '0';
int number2 = num2.charAt(j) - '0';
int sum = number1 + number2 + carry;
carry = sum / 10;
sb.append(sum % 10);
i--;
j--;
}
}
if (carry != 0) {
sb.append(carry);
}
return sb.reverse().toString();
}
}
和 add list 差不多。
Anyway, Good luck, Richardo! — 10/12/2016