Given two non-negative integers, num1
and num2
represented as string, return the sum of num1
and num2
as a string.
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"
Constraints:
1 <= num1.length, num2.length <= 104
num1
andnum2
consist of only digits.num1
andnum2
don't have any leading zeros except for the zero itself.
Follow up: Could you solve it without using any built-in BigInteger
library or converting the inputs to integer directly?
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
n1, n2 = len(num1) - 1, len(num2) - 1
carry = 0
res = []
while n1 >= 0 or n2 >= 0 or carry > 0:
carry += (0 if n1 < 0 else int(num1[n1])) + (0 if n2 < 0 else int(num2[n2]))
res.append(str(carry % 10))
carry //= 10
n1, n2 = n1 - 1, n2 - 1
return ''.join(res[::-1])
class Solution {
public String addStrings(String num1, String num2) {
int n1 = num1.length() - 1, n2 = num2.length() - 1;
int carry = 0;
StringBuilder sb = new StringBuilder();
while (n1 >= 0 || n2 >= 0 || carry > 0) {
carry += (n1 < 0 ? 0 : num1.charAt(n1--) - '0') + (n2 < 0 ? 0 : num2.charAt(n2--) - '0');
sb.append(carry % 10);
carry /= 10;
}
return sb.reverse().toString();
}
}