simulation/add-strings
优质
小牛编辑
128浏览
2023-12-01
Add Strings
描述
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits 0-9. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
分析
这题与 Add Binary 一模一样,将它的代码中的 2 改为 10 即可。
代码
// Add Strings
// Time Complexity: O(max(m,n)), Space Complexity: O(max(m,n))
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder result = new StringBuilder();
int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
while(i >= 0 || j >= 0 || carry > 0) {
int x = i < 0 ? 0 : num1.charAt(i--) - '0';
int y = j < 0 ? 0 : num2.charAt(j--) - '0';
int sum = x + y + carry;
result.append(sum % 10);
carry = sum / 10;
}
return result.reverse().toString();
}
};
// Add Strings
// Time Complexity: O(max(m,n)), Space Complexity: O(max(m,n))
class Solution {
public:
string addStrings(string num1, string num2) {
string result;
int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
while(i >= 0 || j >= 0 || carry > 0) {
int x = i < 0 ? 0 : num1[i--] - '0';
int y = j < 0 ? 0 : num2[j--] - '0';
int sum = x + y + carry;
result.insert(result.begin(), (sum % 10) + '0');
carry = sum / 10;
}
return result;
}
};