#include using namespace std;

template class SeqList { private: DataType data[1000]; int length; // 当前顺序表的长度 public: SeqList(DataType a[], int n) { length = n; for (int i = 0; i < n; i++) { data[i] = a[i]; } }

int Length() { return length; }

DataType Get(int i) { return data[i]; }

void Insert(int i, DataType x) { for (int j = length; j > i; j--) { data[j] = data[j - 1]; } data[i] = x; length++; }

DataType Delete(int i) { DataType x = data[i]; for (int j = i; j < length - 1; j++) { data[j] = data[j + 1]; } length--; return x; } };

template SeqList Add(SeqList A, SeqList B) { int lengthA = A.Length(); int lengthB = B.Length(); int len = lengthA > lengthB ? lengthA : lengthB; SeqList C; for (int i = 0; i < len; i++) { DataType sum = A.Get(i) + B.Get(i); C.Insert(i, sum); } return C; }

template SeqList Mult(SeqList A, SeqList B) { int lengthA = A.Length(); int lengthB = B.Length(); int len = lengthA + lengthB; SeqList C; for (int i = 0; i < len; i++) { C.Insert(i, 0); } for (int i = 0; i < lengthA; i++) { for (int j = 0; j < lengthB; j++) { DataType mul = A.Get(i) * B.Get(j); C.Insert(i + j, C.Get(i + j) + mul % 10); C.Insert(i + j + 1, C.Get(i + j + 1) + mul / 10); } } if (C.Get(len - 1) == 0) { C.Delete(len - 1); } return C; }

int main() { int n; cin >> n; int a[1000]; for (int i = 0; i < n; i++) { cin >> a[i]; } SeqList A(a, n);

SeqList B(a, n);

SeqList C = Add(A, B); int lengthC = C.Length(); cout << lengthC << " "; for (int i = lengthC - 1; i >= 0; i--) { cout << C.Get(i) << " "; } cout << endl;

SeqList D = Mult(A, B); int lengthD = D.Length(); cout << lengthD << " "; for (int i = lengthD - 1; i >= 0; i--) { cout << D.Get(i) << " "; } cout << endl;

return 0; }

C++模板实现顺序表类:大整数加法与乘法

原文地址: https://www.cveoy.top/t/topic/lZRj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录