库“algorithm”中的reverse()函数在 大数相乘、大数相加十分便利,先将大数相加的代码在此做一个记录
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
string add(string num1, string num2)
{
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int carry = 0, i = 0, j = 0;
string ans;
while(i<num1.size() || j<num2.size())
{
int temp;
if(i<num1.size() && j<num2.size())
{
temp = (num1[i] - '0') + (num2[j] - '0') + carry;
i++;
j++;
}
else if(i<num1.size() && j>=num2.size())
{
temp = (num1[i] - '0') + carry;
i++;
}
else if(i>=num1.size() && j<num2.size())
{
temp = num2[j] - '0' + carry;
j++;
}
ans.insert(ans.size(), to_string(temp%10));
carry = temp / 10;
}
if(carry > 0) ans.insert(ans.size(), to_string(carry));
reverse(ans.begin(), ans.end());
return ans;
}
int main()
{
string a = "123456", b = "456789";
string result = add(a, b);
cout<<a<<"+"<<b<<"="<<result;
return 0;
}