这道题十分有十二分之困难(easy)
算法一:直接算
#include<iostream>
using namespace std;
int main(){
int a , b;
cin >> a >> b;
cout << a + b;
return 0;
}
算法二:高精度(详见算法基础课)
#include <iostream>
#include <vector>
using namespace std;
const int N = 10e6 + 10;
vector<int> add(vector<int> &A, vector<int> &B) // C = A + B, A >= 0, B >= 0
{
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;
}
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 --) cout << C[i];
return 0;
}
如果你不会用vector还可以这么做:
#include <iostream>
using namespace std;
const int N = 10e6 +10;
int A[N] , B[N] , C[N];
int Add(int a[], int b[] , int c[] , int cnt){
int t = 0 ;
for (int i = 1 ; i <= cnt ; i ++){
t += a[i] + b[i];
c[i] = t % 10;
t = t / 10;
}
if (t) c[++cnt] = 1;
return cnt;
}
int main()
{
string a , b;
cin >> a >> b;
int cnt1 = 0 , cnt2;
for (int i = a.size() - 1 ; i >= 0 ; i --) A[++cnt1] = a[i] - '0';
for (int i = b.size() - 1 ; i >= 0 ; i --) B[++cnt2] = b[i] - '0';
int tot = Add(A , B , C, max(cnt1 , cnt2));
for (int i = tot ; i >= 1 ; i --) cout << C[i];
return 0;
}