AcWing 791. 高精度加法(C++/Java)
原题链接
简单
作者:
xybh
,
2020-09-03 17:39:55
,
所有人可见
,
阅读 352
C++实现
#include<iostream>
#include<vector>
using namespace std;
vector<int> add(vector<int> &a, vector<int> &b){
vector<int> ans;
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];
ans.push_back(t%10);
t /= 10;
}
if(t) ans.push_back(t);
return ans;
}
int main(){
string a, b;
vector<int>A, B;
cin >> 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');
auto C = add(A,B);
for(int i = C.size()-1; i >= 0; i--) printf("%d", C[i]);
return 0;
}
Java实现
import java.io.*;
import java.math.BigInteger;
class Main {
public static void main(String[] args) throws IOException{
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String[] s = cin.readLine().split(" ");
BigInteger n = new BigInteger(s[0]);
s = cin.readLine().split(" ");
BigInteger m = new BigInteger(s[0]);
System.out.println(m.add(n));
}
}