使用string实现大数加法(C++)
话不多说 直接上代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string splus(string x, string y)
{
string ans = "0";
int xlen = x.length(); int ylen = y.length();
reverse(x.begin(), x.end()); reverse(y.begin(), y.end());
int maxlen = xlen > ylen ? xlen : ylen;
int minlen = xlen < ylen ? xlen : ylen;
for (int i = 0 ; i < minlen ; i++)
{
int currentans = x[i] + y[i] + ans[i] - '0' * 3;
ans[i] = currentans % 10 + '0';
if (currentans > 9)
ans.append("1");
else
ans.append("0");
}
for (int i = minlen; i < maxlen; i++)
{
int currentans;
if (maxlen == xlen)
currentans = x[i] - '0';
else
currentans = y[i] - '0';
currentans += ans[i] - '0';
ans[i] = currentans % 10 + '0';
if (currentans > 9)
ans.append("1");
else
ans.append("0");
}
if(ans[maxlen] == '0')
ans.erase(maxlen);
reverse(ans.begin(), ans.end());
return ans;
}