以字符串的形式给出两个非负整数 num1
和 num2
,返回 num1
和 num2
的和。
样例
给定 num1 = "123"
,num2 = "45"
返回 "168"
解题思路:
按位相加即可。注意最后的进位需要考虑。
class Solution {
public:
/**
* @param num1: a non-negative integers
* @param num2: a non-negative integers
* @return: return sum of num1 and num2
*/
string addStrings(string &num1, string &num2)
{
// write your code here
if(num1.empty() || num2.empty())
return "";
int n1 = num1.size()-1;
int n2 = num2.size()-1;
int cnt = 0;
string res;
while(n1>=0 || n2>=0)
{
int a = (n1>=0)?num1[n1]-'0':0;
int b = (n2>=0)?num2[n2]-'0':0;
int tmp = a + b + cnt;
res += tmp%10 + '0';
cnt = tmp/10;
n1--;
n2--;
}
if(cnt)
res += '1';
reverse(res.begin(),res.end());
return res;
}
};