原题:
Given two non-negative integers
num1
andnum2
represented as string, return the sum ofnum1
andnum2
.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 integer directly.
非零开头的两个超长非负数字的加法,很简单,结果:
Success
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Add Strings.
Memory Usage: 8.9 MB, less than 90.99% of C++ online submissions for Add Strings.
代码:
class Solution {
public:
string addStrings(string num1, string num2) {
string res="";
int i=num1.size()-1,j=num2.size()-1;
bool add=0;
while(i>=0&&j>=0){
int temp=num1[i]+num2[j]-96+add;
if(temp>9){add=1;temp=temp-10;}
else{add=0;}
res+='0'+temp;
i--;
j--;
}
while(i>=0){
int temp=num1[i]+add-48;
if(temp>9){add=1;temp=temp-10;}
else{add=0;}
res+='0'+temp;
i--;
}
while(j>=0){
int temp=num2[j]+add-48;
if(temp>9){add=1;temp=temp-10;}
else{add=0;}
res+='0'+temp;
j--;
}
if(add){res+='1';}
reverse(res.begin(),res.end());
return res;
}
};