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; } intmain() { string a, b; vector <int> A, B; cin >> a >> b;// a = "123456" for (int i = a.size( )-1;i >= 0;--i) A.push_back(a[i] - '0');//{6,5,4,3,2,1} 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]; } return0; }
2.高精度减法
思想:分别用两个数组逆存储两个整数的值,数组下标为0的值存储个位,为1存在十位,以此类推;
提前判断A,B的谁大谁小,使得最终能够大数减小数,如果是B-A,还要提前打印一个负号
再通过模拟减法运算,将得到的值的每一位存储的新数组当中,得到相减数,最后注意前导0的存在
模板
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> #include<vector> using namespace std; boolcmp(vector<int>& A, vector<int>& B)//判断A是否大于等于B { if (A.size() != B.size()) return A.size() > B.size(); for (int i = A.size() - 1;i >= 0;--i) { if (A[i] != B[i]) return A[i]>B[i]; } returntrue; } vector<int> Sub(vector<int>& A, vector<int>& B) { vector<int> C; int t = 0; for (int i = 0;i < A.size();++i) { t = A[i] - t; if (i < B.size()) t -= B[i];// 检测B是否越界 C.push_back((t + 10) % 10);//t为正数与t为负数两种情况判断 // 比如7-8 是负数,模拟减法后则为10+7-8,之后也要后面一位减1 if (t < 0) t = 1; else t = 0; } while (C.size() > 1 && C.back() == 0) C.pop_back(); //防止前导0的存在,需要去0 return C; } intmain() { 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'); if (cmp(A, B)) { auto C = Sub(A, B); for (int i = C.size() - 1;i >= 0;--i) cout << C[i]; } else { auto C = Sub(B, A); cout << '-'; for (int i = C.size() - 1;i >= 0;--i) cout << C[i]; } return0; }