AcWing 792. 高精度减法
原题链接
简单
#include<bits/stdc++.h>
using namespace std;
vector<int> sub(vector<int> &a,vector<int>&b)
{
vector<int> c;
for(int i=0,t=0; i < a.size(); ++i)
{
t = a[i]-t;
if(i<b.size()) t -= b[i];
c.push_back((t+10)%10);
if(t < 0) t = 1;
else t = 0;
}
while(c.size() > 1 && c.back() == 0) c.pop_back();
return c;
}
bool judge(vector<int> &a,vector<int> &b)
{
if(a.size() > b.size()) return 1;
else if(a.size() < b.size()) return 0;
for(int i = a.size()-1; ~i; --i)
if(a[i] > b[i]) return 1;
else if(a[i] < b[i]) return 0;
return 1;
}
int main()
{
string s1,s2;
vector<int> v1,v2;
cin >> s1 >> s2;
for(int i = s1.size()-1; ~i; i--) v1.push_back(s1[i]-'0');
for(int i = s2.size()-1; ~i; i--) v2.push_back(s2[i]-'0');
if(judge(v1,v2))
{
vector<int> res = sub(v1,v2);
for(int i =res.size()-1; ~i; i--) cout << res[i];
}
else
{
vector<int> res = sub(v2,v1);
cout << "-";
for(int i = res.size()-1; ~i; i--) cout << res[i];
}
return 0;
}