【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;
}
相关推荐
newki15 分钟前
学习笔记,Linux虚拟机中C/C++的编译相关流程步骤
c语言·c++
jerry60944 分钟前
c++流对象
开发语言·c++·算法
虾球xz1 小时前
游戏引擎学习第247天:简化DEBUG_VALUE
c++·学习·游戏引擎
superior tigre2 小时前
C++学习:六个月从基础到就业——模板编程:模板特化
开发语言·c++·学习
码农新猿类2 小时前
信号量函数
linux·c++·visual studio
·醉挽清风·2 小时前
学习笔记—双指针算法—移动零
c++·笔记·学习·算法
Ayanami_Reii3 小时前
Leetcode837.新21点
c++·笔记·算法
simple_whu4 小时前
Visual Studio C/C++编译器cl.exe的/source-charset与/execution-charset设置项
c语言·c++·visual studio
GOATLong4 小时前
网络基础概念
linux·运维·服务器·网络·arm开发·c++
工藤新一¹4 小时前
C++/SDL 进阶游戏开发 —— 双人塔防(代号:村庄保卫战 14)
开发语言·c++·游戏引擎·游戏开发·sdl·实践项目