高精度 AcWing 791. 高精度加法
原题链接
算法标签
高精度
代码
#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);
}
vector<int> add(vector<int> &a, vector<int> &b){
vector<int> c;
if(a.size()<b.size()){
return add(b, a);
}else{
int t=0;
rep(i, 0, a.size()){
t+=a[i];
if(i<b.size()){
t+=b[i];
}
c.push_back(t%10);
t/=10;
}
if(t){
c.push_back(t);
}
}
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=add(va, vb);
Rep(i, c.size()-1, -1){
printf("%lld", c[i]);
}
return 0;
}
模板
vector<int> add(vector<int> &A, vector<int> &B){
if (A.size() < B.size()) return add(B, A);
vector<int> C;
int t = 0;
for (int i = 0; i < A.size(); i ++ ){
t += A[i];
if (i < B.size()) t += B[i];
C.push_back(t % 10);
t /= 10;
}
if (t) C.push_back(t);
return C;
}
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈