【AcWing】【C++】高精度加减法模板

高精度加减法模板

这一部分来自于AcWing算法基础课中高精度加减法模板的重新实现,使用C++进行编程,与y总给出的模板基本一致。

亮点在于使用C++的vector来对大整数进行存储,在本科阶段的C语言课程中,通常使用char数组来对大整数进行保存并直接参与运算,后者较难理解。

高精度加法

cpp 复制代码
#include <vector>
#include <string>
#include <iostream>
using namespace std;

string a, b;
vector<int> A, B;

vector<int> add(vector<int> &A, vector<int> &B) {
    int t = 0;
    vector<int> C;
    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;
}

int main() 
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    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--)    cout << C[i];
    return 0;
}

高精度减法

cpp 复制代码
#include <vector>
#include <string>
#include <iostream>
using namespace std;

string a, b;
vector<int> A, B;

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[C.size()-1] == 0 && C.size() > 1)   C.pop_back();
    return C;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    cin >> a >> b;
    bool swap_flag = false;
    if((a.length() > b.length()) || (a.length() == b.length() && a > b)) {
        swap(a, b);
        swap_flag = true;
    }

    for(int i=a.length()-1; i>=0; i--)  A.push_back(a[i] - '0');
    for(int i=b.length()-1; i>=0; i--)  B.push_back(b[i] - '0');

    auto C = sub(B, A);
    if(swap_flag && C.size() != 0 && C[C.size()-1] != 0)    cout << "-";
    for(int i=C.size()-1; i>=0; i--)    cout << C[i];
    return 0;
}
相关推荐
不想写代码的星星2 小时前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星5 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛7 天前
delete又未完全delete
c++
端平入洛8 天前
auto有时不auto
c++
哇哈哈20219 天前
信号量和信号
linux·c++
多恩Stone9 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马9 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost