https://leetcode.com/problems/add-strings/description/
Solution 1. Use the input string to store the result.
string addStrings(string num1, string num2) {
if(num1.size() < num2.size()) return addStrings(num2, num1);
int i = num1.size()-1, j = num2.size()-1, c = 0, t = 0;
for(; i>=0 && (j>=0 || c); j--, i--) {
t = num1[i] - '0' + (j>=0 ? num2[j] -'0' : 0) + c;
num1[i] = t%10 + '0';
c = t/10;
}
return (c? "1":"") + num1;
}
Solution 2.
string addStrings(string num1, string num2) {
if(num1.size() < num2.size()) return addStrings(num2, num1);
string res;
int i, j, c = 0, t=0;
for(j=num2.size()-1, i=num1.size()-1; j>=0; j--, i--) {
t = num2[j] - '0' + num1[i] -'0' + c;
res = to_string(t%10) + res;
c = t/10;
}
while(i>=0) {
t = num1[i] - '0' + c;
res = to_string(t%10) + res;
c = t/10;
i--;
}
if(c)
res = to_string(c) + res;
return res;
}
No comments:
Post a Comment