【高精度算法C++模板】

前言

本篇展示高精度算法的模板。
高精度算法是入门级别算法, 互联网有太多好的教学材料。 笔者就不详细写高精度算法原理了。
有关于高精度原理可以参考以下几篇:
oi-wiki高精度算法
wiki

高精度四则运算

  • 高精度加法
  • 高精度减法
  • 高精度乘法:高精度 × \times × 低精度, 高精度 × \times ×高精度
  • 高精度除法: 高精度 ÷ \div ÷ 低精度。 高精度 ÷ \div ÷高精度(笔者没学过,没有代码)

Tip:
高精度算法是模拟竖式运算的过程
数组0下标开始从低位到高位存储
减法乘法除法需要补充去除前导0的过程

高精度加法

测试链接:
Luogu:1601
ACW高精度加法
LC字符串相加
LC数组形式整数加法

luogu1601:

#include <iostream>
#include <vector>
#include <string>
#include<algorithm>
using std::cin;
using std::cout;
using std::endl;

// 高精度加法
std::string add(const std::string& a, const std::string& b) {
   
    std::vector<int> A, B;

    // 将字符串 a 转换成数字数组 A
    for (int i = a.size() - 1; i >= 0; i--) {
   
        A.push_back(a[i] - '0');
    }

    // 将字符串 b 转换成数字数组 B
    for (int i = b.size() - 1; i >= 0; i--) {
   
        B.push_back(b[i] - '0');
    }

    // 执行加法
    std::string c;
    int n1 = a.size(), n2 = b.size();
    int t = 0;  // 进位
    for (int i = 0; i < n1 || i < n2 || t; i++) {
   
        if (i < n1) t += A[i];  // 如果 A 中还有数字,加上该位
        if (i < n2) t += B[i];  // 如果 B 中还有数字,加上该位

        c.push_back(t % 10 + '0');  // 当前位数的结果
        t /= 10;  // 更新进位
    }

    // 结果字符串已经是逆序的,因此需要将其反转
    std::reverse(c.begin(), c.end());
    
    return c;
}

int main() {
   
    std::string a, b;
    getline(cin, a);  // 输入第一个大整数
    getline(cin, b);  // 输入第二个大整数

    // 输出加法结果
    cout << add(a, b) << endl;

    return 0;
}

ACW

#include<cstdio>
#include<iostream>
#include<vector>
#include<string>
using namespace std;

vector<int> add(const vector<int>& A, const vector<int>& B){
   
    vector<int> C;
    int t=0;
    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(){
   
    string a
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值