高精度减法
Point:
1、计算减法先比较大小
2、公式
$$ tmp = a[i] - tmp - (i < b.size() \; ? \; b[i] \; : \; 0)$$
3、注意前导零
#include <iostream>
#include <vector>
using namespace std;
// >= or <
bool cmp(vector<int>& a, vector<int>& b)
{
if(a.size() != b.size()) return a.size() > b.size();
for(int i = a.size() - 1; i >= 0; -- i)
if(a[i] != b[i]) return a[i] > b[i];
return true;
}
// 减法
vector<int> sub(vector<int>& a, vector<int>& b)
{
vector<int> c;
int t = 0;
for(int i = 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;
}
int main()
{
string x, y;
cin >> x >> y;
vector<int> a, b;
for(int i = x.size() - 1; i >= 0; -- i) a.push_back(x[i] - '0');
for(int i = y.size() - 1; i >= 0; -- i) b.push_back(y[i] - '0');
if(cmp(a, b))
{
a = sub(a, b);
for(int i = a.size() - 1; i >= 0; -- i) cout << a[i];
}
else
{
a = sub(b, a);
cout << "-";
for(int i = a.size() - 1; i >= 0; -- i) cout << a[i];
}
return 0;
}