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 digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integerdirectly.
class Solution {
public:
string addStrings(string num1, string num2) {
if (num1.empty()) {
return num2;
}
if (num2.empty()) {
return num1;
}
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
string ans;
int carry = 0;
int i = 0;
while (i < num1.size() || i < num2.size()) {
int first = (i < num1.size() ? num1[i] - '0' : 0);
int second = (i < num2.size() ? num2[i] - '0' : 0);
int sum = first + second + carry;
ans += to_string(sum % 10);
carry = sum / 10;
i++;
}
if (carry) {
ans += to_string(carry);
}
reverse(ans.begin(), ans.end());
return ans;
}
};
========= Better one and optimize =======
string addStrings(string num1, string num2) {
int size1 = num1.size();
int size2 = num2.size();
int size = max(size1, size2);
string ans;
ans.resize(size + 1);
int iter = size, iter1 = size1 - 1, iter2 = size2 - 1;
int carry = 0;
while (iter1 >= 0 || iter2 >= 0) {
int dig1 = (iter1 >= 0 ? num1[iter1] - '0': 0);
int dig2 = (iter2 >= 0 ? num2[iter2] - '0': 0);
ans[iter--] = '0' + ((carry + dig1 + dig2) % 10);
carry = (carry + dig1 + dig2) / 10;
iter1--;
iter2--;
}
if (carry != 0) {
ans[0] = '0' + carry;
return ans;
}
return ans.substr(1);
}
No comments:
Post a Comment