Given two non-negative numbers 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.
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
string addStrings(string num1, string num2)
{
int x=num1.size(),
y=num2.size(),
i,carry,temp;
vector<int>ret;
if(x==0&&y==0)
return "";
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
carry=0;
for(i=0;i<x&&i<y;i++)
{
temp=(num1[i]-'0')+(num2[i]-'0')+carry;
carry=temp/10;
ret.push_back(temp%10);
}
while(i<x)
{
temp=num1[i]-'0'+carry;
carry=temp/10;
ret.push_back(temp%10);
i++;
}
while(i<y)
{
temp=num2[i]-'0'+carry;
carry=temp/10;
ret.push_back(temp%10);
i++;
}
if(carry>0)
ret.push_back(carry);
string s;
for(i=ret.size()-1;i>=0;i--)//将整数数组转化为字符串
{
char c=ret[i]+'0';
s=s+c;
}
return s;
}
};
int main()
{
string num1,num2;
cin>>num1>>num2;
string result;
Solution solve;
cout<<solve.addStrings(num1,num2)<<endl;
return 0;
}