1,题目要求
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
也就是给定两个字符串形式的数字,进行相加, 然后返回一个字符串。
不允许直接使用字符串转换成数字的内置方法。
2,题目思路
一开始觉得直接用ASCII和字符的对应关系直接进行转换相加,虽然可以实现两个数的相加,但是当num1太大时(num的长度可能在5100左右,过大)int或者long或者其他形式的数字都无法存储。
因此不能进行数值形式的相加,而是需要进行字符串的按位处理。、
每次处理一位,然后对所得到的进位进行记录,进行一位一位的相加。
3,程序源码
class Solution {
public:
string addStrings(string num1, string num2) {
long len1 = num1.size()-1,len2 = num2.size()-1;
vector<string> resVector;
string res;
int carry = 0;//进位的表示
while(len1>=0||len2>=0||carry>0)
{
int tempSum = 0;
int tempRes = 0;
if(len1>=0)
{
tempSum += num1[len1]-'0';//得到数字(int型)
len1--;
}
if(len2>=0)
{
tempSum +=num2[len2]-'0';
len2--;
}
tempSum += carry;//根据上一次的进位更新
carry = tempSum/10;//计算新的进位,因为两个数的加和很可能大于0;
tempRes = tempSum%10;//个位作为结果位
res += to_string(tempRes);
}
reverse(res.begin(),res.end());
return res;
}
};
因为对于num1和num2都是从字符串的末尾开始进行操作的,也就是最小的部分,而在最后的字符串相加时都是在所得字符串末尾相加,因此得到的结果还需要进行reverse操作得到正确的字符串。