1 #include <bits/stdc++.h> 2 using namespace std; 3 vector<int> add(vector<int> &A, vector<int> &B) { //加上引用,不然很慢 4 vector<int> C; //答案 5 int t = 0; //进位 6 for (int i = 0; i < A.size() || i < B.size(); i++) { 7 //让t来表示三个数的和 8 if (i < A.size()) { 9 t += A[i]; 10 } 11 if (i < B.size()) { 12 t += B[i]; 13 } 14 C.push_back(t % 10); 15 t /= 10; 16 } 17 if (t) { 18 C.push_back(1); 19 } 20 return C; 21 } 22 int main() { 23 string a, b; //太长了,所以用字符串来读入 24 cin >> a >> b; 25 vector<int> A, B; //然后存进vector 26 for (int i = a.length() - 1; i >= 0; i--) { 27 A.push_back(a[i] - '0'); //字符变数字 28 } 29 for (int i = b.length() - 1; i >= 0; i--) { 30 B.push_back(b[i] - '0'); 31 } 32 vector<int> C = add(A, B); 33 for (int i = C.size() - 1; i >= 0; i--) { 34 cout << C[i]; 35 } 36 return 0; 37 }
2020年9月29日更新: 高精度压位压8位的做法
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int base = 100000000; 4 vector<int> add(vector<int> &A, vector<int> &B) { 5 vector<int> C; 6 int t = 0; 7 for (int i = 0; i < A.size() || i < B.size(); i++) { 8 if (i < A.size()) { 9 t += A[i]; 10 } 11 if (i < B.size()) { 12 t += B[i]; 13 } 14 C.push_back(t % base); 15 t /= base; 16 } 17 if (t) { 18 C.push_back(t); 19 } 20 return C; 21 } 22 int main() { 23 string a, b; 24 cin >> a >> b; 25 vector<int> A, B, C; 26 for (int i = a.size() - 1, s = 0, j = 0, t = 1; i >= 0; i--) { 27 s += (a[i] - '0') * t; 28 j++; 29 t *= 10; 30 if (j == 8 || i == 0) { 31 A.push_back(s); 32 s = 0; 33 j = 0; 34 t = 1; 35 } 36 } 37 for (int i = b.size() - 1, s = 0, j = 0, t = 1; i >= 0; i--) { 38 s += (b[i] - '0') * t; 39 j++; 40 t *= 10; 41 if (j == 8 || i == 0) { 42 B.push_back(s); 43 s = 0; 44 j = 0; 45 t = 1; 46 } 47 } 48 C = add(A, B); 49 cout << C.back(); 50 for (int i = C.size() - 2; i >= 0; i--) { 51 printf("%08d", C[i]); 52 } 53 return 0; 54 }