415. 字符串相加

class Solution {
public:
string addStrings(string num1, string num2) {
//就是大整数相加，从后往前加，只要有一个字符串没遍历完就要继续，如果还有carry也要继续
//最后将res反转即可
string res = "";
int len1 = num1.length()-1, len2 = num2.length()-1;
int sum = 0, carry = 0;
int a = 0, b = 0;
while(len1 >= 0 || len2>=0 ||carry != 0){
a = (len1 < 0 ? 0 : num1[len1--]-'0');
b = (len2 < 0 ? 0 : num2[len2--]-'0');
sum = (a+b+carry)%10;
carry = (a+b+carry)/10;
res += (sum+'0');
}
reverse(res.begin(),res.end());
return res;
}
};

class Solution {
public:
string addStrings(string num1, string num2) {
//也是类似大整数相加，num1或者num2没遍历完，或者carry==1的情况下都不要退出
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
int index1 = 0, index2 = 0;
int carry = 0;
int sum = 0;
string res = "";
int tmp1 = 0, tmp2 = 0;
while(index1 < num1.length() || index2 < num2.length() || carry != 0){
tmp1 = (index1 == num1.length() ? 0 : num1[index1++]-'0');
tmp2 = (index2 == num2.length() ? 0 : num2[index2++]-'0');
sum = (tmp1 + tmp2 + carry)%10;
carry = (tmp1 + tmp2 +carry)/10;
res += (sum+'0');
}
reverse(res.begin(),res.end());
return res;
}
};

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

baixiaofei567

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

12-08 547