Given two non-negative integers num1 and num2 as strings, compute their sum and return the same as strings.
You cannot use any of the built-in libraries for handling large integers (such as BigInteger), nor can you directly convert input strings to integer form.
Example 1:
Input: num1 = "11", num2 = "123"
Output: "134"
Example 2:
Input: num1 = "456", num2 = "77"
Output: "533"
Example 3:
Input: num1 = "0", num2 = "0"
Output: "0"
hint:
1 <= num1.length, num2.length <= 104
Both num1 and num2 contain only digits 0-9
Neither num1 nor num2 contain any leading zeros
Source: LeetCode
Link: https://leetcode.cn/problems/add-strings
The copyright belongs to LeetCode. For commercial reprints, please contact the official authorization, for non-commercial reprints, please indicate the source.
class Solution {
public String addStrings(String num1, String num2) {
int i = num1.length() - 1;
int j = num2.length() - 1;
StringBuffer ans = new StringBuffer();
int add = 0;
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 = ans.append(result % 10);
add = result / 10;
i--;
j--;
}
ans.reverse();
return ans.toString();
}
}