Ryanlyt / algorithm-learning

The firse
0 stars 0 forks source link

9.17 #9

Open Ryanlyt opened 1 year ago

Ryanlyt commented 1 year ago

高精度

大整数存储

把输入的字符转成整数,减去一个'0'就可以了,如:`A.push_back(a[i] - '0'); _0cc8dcdf17c46cc678123baa778f0585_964698712_Screenshot_2023-09-17-11-07-01-855_com alicloud databox

`

高精度加法

_210dfae4be6e59600f993119b9d95145_1948911286_Screenshot_2023-09-17-11-10-01-211_com alicloud databox _00d04d4f7c46aa92a77a73a2b5147f5b_559646831_Screenshot_2023-09-17-11-23-14-768_com alicloud databox

// C = A + B, A >= 0, B >= 0
vector<int> add(vector<int> &A, vector<int> &B)
{
    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;
}
高精度减法

_89136916aba88f8e50bae30a52ca8dce_-114209226_Screenshot_2023-09-17-11-30-29-192_com alicloud databox _479dd27d65c60dbe4f5ba2a75d1ce5a8_-30141886_Screenshot_2023-09-17-11-38-56-084_com alicloud databox _0d74f7022a51a5ac359a49d2ab4d326b_1397865630_Screenshot_2023-09-17-11-39-04-152_com alicloud databox

// C = A - B, 满足A >= B, A >= 0, B >= 0
vector<int> sub(vector<int> &A, vector<int> &B)
{
    vector<int> C;
    for (int i = 0, t = 0; i < A.size(); i ++ )
    {
        t = A[i] - t;
        if (i < B.size()) t -= B[i];
        C.push_back((t + 10) % 10);
        if (t < 0) t = 1;
        else t = 0;
    }

    while (C.size() > 1 && C.back() == 0) C.pop_back();    //去掉前导0
    return C;
}
高精度乘低精度

_5b1c81c5ab497f9623148dd99f77e9cc_53867708_Screenshot_2023-09-17-11-45-20-221_com alicloud databox _f137577837fb2ba3267aec77f4ada7dc_-1870500628_Screenshot_2023-09-17-11-52-58-305_com alicloud databox

// C = A * b, A >= 0, b >= 0
vector<int> mul(vector<int> &A, int b)
{
    vector<int> C;

    int t = 0;
    for (int i = 0; i < A.size() || t; i ++ )
    {
        if (i < A.size()) t += A[i] * b;    //把b看成一个整体去和a每一位相乘
        C.push_back(t % 10);
        t /= 10;
    }

    while (C.size() > 1 && C.back() == 0) C.pop_back();    // 可以不用

    return C;
}
高精度除以低精度

_3539e3da42dbe5f8605bbe175feb6c61_875627541_Screenshot_2023-09-17-12-04-28-277_com alicloud databox

// A / b = C ... r, A >= 0, b > 0
vector<int> div(vector<int> &A, int b, int &r)
{
    vector<int> C;
    r = 0;
    for (int i = A.size() - 1; i >= 0; i -- )    //除法是从最高位开始算的
    {
        r = r * 10 + A[i];
        C.push_back(r / b);
        r %= b;
    }
    reverse(C.begin(), C.end());
    while (C.size() > 1 && C.back() == 0) C.pop_back();
    return C;
}

reverse(a.begin(), b.end());