高精度减法
作者:
索隆
,
2021-11-05 16:07:19
,
所有人可见
,
阅读 204
#include<iostream>
#include<vector>
using namespace std;
//判断a-b>=0
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){
int t = 0;
vector<int> c;
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 = 0;
else t = 1;
}
while(c.back() == 0 && c.size() > 1)
c.pop_back();//去掉前导零
return c;
}
int main(){
string x, y;
vector<int> a, b;
cin >> x >> y;
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');
vector<int> c;
if(cmp(a, b)) {
c = sub(a, b);
}
else{
c = sub(b, a);
printf("%s", "-");
}
for(int i = c.size() - 1; i >= 0; i --) printf("%d", c[i]);
return 0;
}