• 【洛谷】P1601 A+B Problem 高精(高精度加法模板)


    加法高精度模板

    【洛谷】P1601 A+B Problem 高精

    原理

    高精度计算一般用到数组。
    把输入的数字倒着存就可以实现竖式计算里面向右对齐。
    最后再判断进位,输出时最高位特判即可。

    代码

    /* P1601 A+B Problem 高精
     * 来源:洛谷
     * 作者:RainbowBird
     * 日期:2020年6月6日
     * 算法:高精度加法
     */
    
    #include <algorithm>
    #include <cstdio>
    #include <cstring>
    #include <iostream>
    using namespace std;
    
    int a[505], b[505], c[505];
    char stra[505], strb[505];
    
    int main() {
        scanf("%s %s", &stra, &strb);
        int lena = strlen(stra);
        int lenb = strlen(strb);
        int len = max(lena, lenb);
    
        // 靠右对齐
        for (int i = strlen(stra); i > 0; i--)
            a[lena - i + 1] = stra[i - 1] - '0';
        for (int j = strlen(strb); j > 0; j--)
            b[lenb - j + 1] = strb[j - 1] - '0';
    
        // 核心部分
        for (int i = 1; i <= len; i++) {
            c[i] += a[i] + b[i];
            // 判断进位
            if (c[i] >= 10) {
                c[i] -= 10;
                c[i + 1]++;
            }
        }
    
        if (c[len + 1] != 0) // 最高位特判
            printf("%d", c[len + 1]); // 输出最高位
        
        for (int i = len; i > 0; i--) {
            printf("%d", c[i]); // 倒着输出
        }
    
        return 0;
    }
    
  • 相关阅读:
    Java数据类型
    redis的安装
    软件测试(一、二)
    软件开发
    python----基础函数
    Python的web框架
    Python 中的lambda函数介绍
    Python中HTTP协议
    Django基本模块介绍
    Python --------列表
  • 原文地址:https://www.cnblogs.com/luoling8192/p/13054037.html
Copyright © 2020-2023  润新知