高精度 AcWing 792. 高精度减法
原题链接
算法标签
高精度
代码
#include<bits/stdc++.h>
#define int long long
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>b;--i)
using namespace std;
const int N = 100005;
int a[N];
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
void put(int x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) put(x/10);
putchar(x%10^48);
}
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;
rep(i, 0, a.size()){
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;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string a,b;
cin>>a>>b;
vector<int> va, vb;
Rep(i, a.size()-1, -1){
va.push_back(a[i]-'0');
}
Rep(i, b.size()-1, -1){
vb.push_back(b[i]-'0');
}
vector<int> c;
if(cmp(va, vb)){
c=sub(va, vb);
}
else if(!cmp(va, vb)){
c=sub(vb, va);
printf("-");
}
Rep(i, c.size()-1, -1){
printf("%lld", c[i]);
}
return 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;
}
// C = A - B, 满足A >= B, A >= 0, B >= 0
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;
}
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈