AcWing
792. 高精度减法
实质上是,使用数组模拟减法运算的过程。注意消除结果数组中的前导0
.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<int> A, B;
string a, b;
bool cmp(vector<int> &A, vector<int> &B){
int sA = (int)A.size(), sB = (int)B.size();
if(sA != sB) return sA > sB;
for(int i = sA - 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;
int sA = (int)A.size(), sB = (int)B.size();
for(int i = 0; i <= sA - 1; i ++){
t = A[i] - t;
if(i <= sB - 1) t -= B[i];
C.push_back((t + 10) % 10);
if(t < 0) t = 1;
else t = 0;
}
while((int)C.size() >= 2 && !C.back()) C.pop_back();
return C;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> a >> b;
int sa = (int)a.size(), sb = (int)b.size();
for(int i = sa - 1; i >= 0; i --) A.push_back(a[i] - '0');
for(int i = sb - 1; i >= 0; i --) B.push_back(b[i] - '0');
vector<int> C;
if(cmp(A, B)) C = sub(A, B);
else C = sub(B, A), cout << '-';
int sC = (int)C.size();
for(int i = sC - 1; i >= 0; i --) cout << C[i];
return 0;
}