AcWing 792. 高精度减法—58ms
原题链接
简单
作者:
Belous
,
2019-05-19 21:39:05
,
所有人可见
,
阅读 1012
C++11 代码
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string BigIntergerSub(const string &a, const string &b)
{
if (a.size() < b.size() || (a.size() == b.size() && a < b))
return "-" + BigIntergerSub(b, a);
if (a == b)
return string("0");
string ans;
auto i = a.rbegin(), j = b.rbegin();
bool sp = false;
while (j != b.rend())
{
auto temp = (*i - '0') - (*j - '0');
if (sp)
--temp;
sp = false;
if (temp < 0)
{
sp = true;
temp += 10;
}
ans.push_back(temp + '0');
++i, ++j;
}
while (i != a.rend())
{
auto temp = (*i - '0');
if (sp)
--temp;
sp = false;
if (temp < 0)
{
sp = true;
temp += 10;
}
ans.push_back(temp + '0');
++i;
}
reverse(ans.begin(), ans.end());
return ans.substr(ans.find_first_not_of('0'));
}
int main(int argc, char **argv)
{
string a, b;
cin >> a >> b;
cout << BigIntergerSub(a, b) << endl;
return EXIT_SUCCESS;
}