最终版,难度不大,魔鬼细节
class Solution {
public:
string addStrings(string num1, string num2) {
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
string ret;
int i = 0;
int len1 = num1.size();
int len2 = num2.size();
int carry = 0;
while(i < len1 && i < len2){
int a = num1[i] - '0';
int b = num2[i] - '0';
int sum = carry + a + b;
ret += ((sum%10)+'0');
carry = sum/10;
i++;
}
string temp;
if(i == len1){
temp = num2.substr(i);
}else if(i == len2){
temp = num1.substr(i);
}
i = 0;
int len = temp.size();
while(i < len){
if(carry == 0){
string str = temp.substr(i);
if(!str.empty())
ret += str;
break;
}
else {
int a = temp[i] - '0';
int sum = a + carry;
ret += (sum%10 +'0');
carry = sum/10;
}
i++;
}
if(carry)
ret += (carry +'0');
reverse(ret.begin(),ret.end());
return ret;
}
};
第一版,想用库函数偷懒我输了
class Solution {
public:
string addStrings(string num1, string num2) {
long long int res = stoll(num1) + stoll(num2);
return to_string(res);
}
};
第二版,长度不一致的处理不好,里面有多处错误
string addStrings(string num1, string num2) {
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
string ret;
int i = 0;
int len1 = num1.size();
int len2 = num2.size();
int carry = 0;
while(i < len1 && i < len2){
int a = num1[i] - '0';
int b = num2[i] - '0';
int sum = carry + a + b;
ret += ((sum%10)+'0');
carry = sum/10;
i++;
}
string temp;
if(i == len1){
temp = num2.substr(i);
}else if(i == len2){
temp = num2.substr(i);
}
i = 0;
int len = temp.size();
while(i < len){
if(carry == 0){
ret += temp.substr(i);
break;
}
else {
int a = temp[i] - '0';
int sum = a + carry;
ret += (sum%10 - '0');
carry = sum/10;
}
}
if(carry)
ret += (carry -'0');
reverse(ret.begin(),ret.end());
return ret;
}
|