此题与链表相加有异曲同工之妙
class Solution {
public String addStrings(String num1, String num2) {
if(num1 == "0") {
return num2;
}
if(num2 == "0") {
return num1;
}
int i = num1.length() - 1;
int j = num2.length() - 1;
int carry = 0;
int sum = 0;
String str = "";
while(i >= 0 || j >= 0 || carry != 0) {
int a = i < 0? 0 : num1.charAt(i) - '0';
int b = j < 0? 0 : num2.charAt(j) - '0';
sum = a + b + carry;
carry = sum / 10;
sum = sum % 10;
str = sum + str;
i--;
j--;
}
return str;
}
}
class Solution {
public String addStrings(String num1, String num2) {
int i = num1.length() - 1, j = num2.length() - 1, add = 0;
StringBuffer ans = new StringBuffer();
while (i >= 0 || j >= 0 || add != 0) {
int x = i >= 0 ? num1.charAt(i) - '0' : 0;
int y = j >= 0 ? num2.charAt(j) - '0' : 0;
int result = x + y + add;
ans.append(result % 10);
add = result / 10;
i--;
j--;
}
ans.reverse();
return ans.toString();
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/add-strings/solution/zi-fu-chuan-xiang-jia-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。