【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;
}
相关推荐
weixin_307779131 小时前
C++代码实现MATLAB中的dlarray函数功能
开发语言·c++·算法·matlab
Frank_refuel4 小时前
C++11之一场名为“搬家”的 C++ 之旅
开发语言·c++
hetao17338376 小时前
2026-10-03~04 hetao1733837 的刷题记录
c++·算法
longlongzihan7 小时前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
潼心1412o10 小时前
C++初阶(长期更新)第6讲:类和对象(下)
开发语言·c++·算法
-森屿安年-10 小时前
按身高排序
c++·算法
(Charon)11 小时前
【C++面试】vector底层原理:扩容、拷贝移动与迭代器失效
c++·面试
朔北之忘 Clancy12 小时前
青少年软编等考七级题解目录
开发语言·c++·青少年编程·gesp·csp·信奥赛·noi
汉克老师12 小时前
GESP2026年9月认证C++七级( 第一部分选择题(8~15题)精讲
c++·gesp·小学生·学c++编程
Mr_Macallon12 小时前
C++回顾(基础)(01)
c语言·开发语言·c++·学习