AcWing 792. 高精度减法
原题链接
简单
作者:
__43
,
2020-09-24 11:14:12
,
所有人可见
,
阅读 297
#include <iostream>
#include <vector>
using namespace std;
bool cmp(string &s1,string &s2)
{
if (s1.size() != s2.size())
return s1.size() > s2.size();
for (int i = 0;i < s1.size();++i)
if (s1[i] != s2[i]) return s1[i] > s2[i];
return true;
}
vector<int> sub(vector<int>& v1,vector<int>& v2)
{
vector<int> v3;
for (int i = 0,t = 0;i < v1.size();++i)
{
t = v1[i] - t;
if (i < v2.size()) t -= v2[i];
v3.push_back((i + 10) % 10);
t = t < 0 ? 1 : 0;
}
while (v3.size() > 1 && v3.back() == 0) v3.pop_back();
return v3;
}
int main(void)
{
string s1,s2;
cin>>s1>>s2;
vector<int> v1,v2,v3;
for (int i = (int)s1.size() - 1;i > -1;--i)
v1.push_back(s1[i] - '0');
for (int i = (int)s2.size() - 1;i > -1;--i)
v2.push_back(s2[i] - '0');
if (cmp(s1,s2)) v3 = sub(v1,v2);
else v3 = sub(v2,v1),printf("-");
for (int i = (int)v3.size() - 1;i > -1;--i)
printf("%d",v3[i]);
return 0;
}