class Solution {
public:
string addStrings(string num1, string num2) {
int len1=num1.length(),len2=num2.length();
int len=len1>len2?len1:len2;
string s1(len-len1,'0'); //拷贝len-len1个字符'0'到s1
string s2(len-len2,'0');
num1=s1+num1;
num2=s2+num2;
int carry=0;
string sum=num1;
for(int i=len-1;i>=0;i--){
sum[i]=(num1[i]-'0'+num2[i]-'0'+carry)%10+'0';
carry=(num1[i]-'0'+num2[i]-'0'+carry)/10;
}
if(carry>0) sum="1"+sum;
return sum;
}
};
LeetCode-415. 字符串相加-easy
最新推荐文章于 2024-09-06 10:38:06 发布