AcWing 791. 高精度加法
原题链接
简单
作者:
Value
,
2020-04-25 17:47:38
,
所有人可见
,
阅读 498
方法一
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
string a, b;
int main(){
cin >> a >> b;
int cnt = 0;
string res = "";
int i;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
for(i = 0; i < a.size() && i < b.size(); i ++ ){
int num = cnt + a[i] + b[i] - 2 * '0';
if(num >= 10){
cnt = 1;
res += (num - 10 + '0');
}else{
cnt = 0;
res += (num + '0');
}
}
while(i < a.size()){
int num = a[i] - '0' + cnt;
if(num >= 10){
cnt = 1;
res += (num - 10 + '0');
}else{
cnt = 0;
res += (num + '0');
}
i ++ ;
}
while(i < b.size()){
int num = b[i] - '0' + cnt;
if(num >= 10){
cnt = 1;
res += (num - 10 + '0');
}else{
cnt = 0;
res += (num + '0');
}
i ++ ;
}
if(cnt != 0) res += '1';
reverse(res.begin(), res.end());
cout << res << endl;
return 0;
}
方法二(精简版)
#include <iostream>
#include <vector>
using namespace std;
vector<int> add(vector<int> &A, vector<int> &B){
vector<int> C;
int t = 0;
for(int i = 0; i < A.size() || i < B.size(); i ++ ){
if(i < A.size()) t += A[i];
if(i < B.size()) t += B[i];
C.push_back(t % 10);
t /= 10;
}
if(t) C.push_back(1);
return C;
}
int main(){
string a, b; cin >> a >> b;
vector<int> A, B;
for(int i = a.size() - 1; i >= 0; i -- ) A.push_back(a[i] - '0');
for(int i = b.size() - 1; i >= 0; i -- ) B.push_back(b[i] - '0');
vector<int> C = add(A, B);
for(int i = C.size() - 1; i >= 0; i -- ) cout << C[i];
return 0;
}