开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第17天,点击查看活动详情
一、题目描述:
415. 字符串相加 - 力扣(LeetCode) (leetcode-cn.com)
给定两个字符串形式的非负整数
num1和num2,计算它们的和并同样以字符串形式返回。你不能使用任何內建的用于处理大整数的库(比如
BigInteger), 也不能直接将输入的字符串转换为整数形式。
示例 1:
输入:num1 = "11", num2 = "123"
输出:"134"
示例 2:
输入:num1 = "456", num2 = "77"
输出:"533"
示例 3:
输入:num1 = "0", num2 = "0"
输出:"0"
提示:
- 1 <= num1.length, num2.length <= 10^4
- num1 和num2 都只包含数字 0-9
- num1 和num2 都不包含任何前导零
二、思路分析:
- 利用for循环,从字符串末尾至首依次相加
注意:- 字符串每个元素减0化为整数再相加,
- 相加时记得加上weight(进位数)
- 最高位如果有进位数,需要push单字符串
- 将结果逆置: 从尾部开始相加,push到res,因此要逆转过来
三、AC 代码:
class Solution {
public:
string addStrings(string num1, string num2) {
// 进位数
int weight = 0;
int a,b,temp;
string res;
for(int i = num1.length()-1, j = num2.length()-1;i >= 0||j >= 0;i--,j--) {
// 将字符转化为整数
a=b=temp =0;
if (i>=0) a=num1[i]-'0';
if (j>=0) b=num2[j]-'0';
temp =a+b+weight;
res.push_back((temp%10)+'0');
weight = temp /10;
}
// 输出最高位
if(weight != 0) {
res.push_back(weight +'0');
}
// 结果倒转
char t;
for(int i=0;i<res.length()/2;i++) {
t = res[i];
res[i] = res[res.length()-1-i];
res[res.length()-1-i] = t;
}
return res;
}
};
四、参考:
415. 字符串相加 快速判断边界条件:如何在头部补 0 ?如何判断最高位是否进位? - 字符串相加 - 力扣(LeetCode)