1. 程式人生 > 其它 >【高精度加法】Acwing791.高精度加法

【高精度加法】Acwing791.高精度加法

Acwing791.高精度加法

題解

高精度加法

#include <iostream>
#include <cstdio>
#include <vector>

using namespace std;

vector<int> add(vector<int> &a, vector<int> &b)
{
    if(a.size() < b.size()) return add(b, a);
    
    int t = 0;
    vector<int> c;
    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;
}

int main()
{
    vector<int> A;
    vector<int> B;
    
    string 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');
    
    auto C = add(A, B);
    for(int i = C.size() - 1; i >= 0; --i) printf("%d",C[i]);
    puts("");
    
    return 0;
}

壓九位做法

#include <iostream>
#include <cstdio>
#include <vector>

using namespace std;

const int base = 1000000000;

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 % base);
        t /= base;
    }
    if(t) c.push_back(t);
    return c;
}

int main()
{
    vector<int> A;
    vector<int> B;
    
    string a, b;
    cin >> a >> b;
    
    for(int i = a.size() - 1, j = 0, t = 1, s = 0; i >= 0; --i)
    {
        s += (a[i] - '0') * t;
        t *= 10, j++;
        if(j == 9 || i == 0)
        {
            A.push_back(s);
            s = 0, t = 1, j = 0;
        }
    }
    
    for(int i = b.size() - 1, j = 0, t = 1, s = 0; i >= 0; --i)
    {
        s += (b[i] - '0') * t;
        t *= 10, j++;
        if(j == 9 || i == 0)
        {
            B.push_back(s);
            s = 0, t = 1, j = 0;
        }
    }
    
    auto C = add(A, B);
    cout << C.back();
    for(int i = C.size() - 2; i >= 0; --i) printf("%09d",C[i]); //注意輸出細節
    puts("");
    
    return 0;
}