题目描述
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
代码
class Solution {
public:
string addStrings(string num1, string num2) {
int n1 = num1.length();
int n2 = num2.length();
int cnt = max(n1, n2);
string ans(cnt+1, '0');
int p = cnt;
int p1 = n1-1, p2 = n2-1;
int jin = 0;
while(p1>=0 || p2>=0) {
int tmp1 = 0, tmp2 = 0;
if (p1 >= 0) tmp1 = num1[p1] - '0';
if (p2 >= 0) tmp2 = num2[p2] - '0';
int cur = tmp1 + tmp2 + ans[p] - '0';
if (cur >= 10) jin = 1;
else jin = 0;
ans[p-1] = jin + '0';
cur = cur % 10;
ans[p] = cur + '0';
p--;
p1--;
p2--;
}
if (p != -1) {
int pos = p;
if (ans[p] != '0') pos--;
ans.erase(0, pos+1);
}
return ans;
}
};