1 条题解
-
0小羊 LV 7 @ 2022-06-17 17:36:15
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;char a[1222];
char b[1222];
//判断A>=B的结果
bool comp(vector<int> &A, vector<int> &B){
if(A.size()!=B.size()) return A.size()>B.size();
else{//位数相同
for(int i = A.size()-1; i>=0; i--){//高位开始逐位比较
if(A[i]!=B[i]) return A[i]>B[i];
}
}
return true;
}vector<int> subct(vector<int> &A, vector<int> &B)
{ //C=A-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); //当t>0时 插入t%10 当t<0时,借位,t+=10
if(t<0) t = 1; //t<0,扫描从高位借了1,
else t = 0;
}
//删除前导0,如003中的00
while(C.size()>1&&C.back() == 0) C.pop_back();
return C;
}int main(){
cin >> a >> b;
vector<int> A,B;
for(int i = strlen(a)-1; i>=0; i--) A.push_back(a[i]-'0');
for(int i = strlen(b)-1; i>=0; i--) B.push_back(b[i]-'0');if(comp(A,B)){ //A>B
vector<int> C = subct(A,B);
for(int i = C.size() - 1; i>=0; i--) cout << C[i];
}
else{
vector<int> C = subct(B,A);
cout << '-';
for(int i = C.size() - 1; i>=0; i--) cout << C[i];
}
return 0;
}
- 1