| title | 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
num1andnum2is < 5100. - Both
num1andnum2contains only digits 0-9. - Both
num1andnum2does 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 即可。
import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem";
<Tabs defaultValue="java" values={[ { label: 'Java', value: 'java', }, { label: 'C++', value: 'cpp', }, ] }>
// 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;
}
};