#include <iostream>
using namespace std;

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

template <class DataType>
SeqList<DataType> Mult(SeqList<DataType> A, SeqList<DataType> B)
{
    int lengthA = A.Length();
    int lengthB = B.Length();
    int len = lengthA + lengthB;
    SeqList<DataType> 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<int> A(a, n);

    SeqList<int> B(a, n);

    SeqList<int> 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<int> 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;
}

使用示例: 输入: 3 1 2 3 输出: 5 1 2 4 6 8 7 1 5 1 8 4 3 5

顺序表类用C++的模板实现输入大数据位数以及每一位的数字从高位到低位输出结果位数和每一位的数字从高位到低位。大整数位数不超过1000。输入数据示例如下:3 1 2 3 3位数数值为1235 1 2 3 4 5 5位数数值为12345加法结果输出数据如下:5 1 2 4 6 8 5位数数值为12468乘法结果输出数据如下:7 1 5 1 8 4 3 5 7位数数值为15184351、模板类的使用课本

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

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