415. Add Strings
原创
©著作权归作者所有:来自51CTO博客作者小虎AI实验室的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目:
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
- Both
num1
- and
num2
- contains only digits
0-9
- .
- Both
num1
- and
num2
- You must not use any built-in BigInteger library or convert the inputs to integer
思路:
本题本质上十进制加法运算,满十进1,题目无非将数值转换成字符串,可以各位减‘0‘求得大小
代码:
class Solution {
public:
string addStrings(string num1, string num2) {
int i =num1.size()-1,j=num2.size()-1;
int carry = 0;
string res ="";
while(i>=0||j>=0||carry)
{
int sum = 0;
sum +=carry;
if(i>=0)
{
sum += (num1[i] - '0');
i--;
}
if(j>=0)
{
sum+=(num2[j] - '0');
j--;
}
carry = sum / 10;
sum = sum % 10;
res += to_string(sum);
}
reverse(res.begin(),res.end());
return res;
}
};