JDOJ 1789: 高精度A+B JDOJ 1789: 高精度A+B 洛谷 P1601 A+B Problem(高精)

JDOJ传送门

洛谷 P1601 A+B Problem(高精)

洛谷传送门

Description

已知两个整数A、B

求A+B

Input

第一行为A

第二行为B

Output

输出一行为A+B的结果

Sample Input

5 6

Sample Output

11

HINT

0 <= A, B <= (10^{100000})

题解:

100000位的大整数加法,不考虑负数。

一道高精度的板子题。

所谓高精度其实就是代码模拟加法的竖式运算,对于这样一道板子题来讲,我简单说一下高精度加法的实现过程:

字符串读入

字符串转数字,从后往前转

模拟竖式运算进行加法。

去除前导0,进行输出。

聪明一点的看代码就能看懂什么意思:

#include<cstdio>
#include<cstring>
#include<algorithm>
#pragma GCC optimize(1)
#pragma GCC optimize(2)
#pragma GCC optimize(3)
using namespace std;
const int maxx=1e5+1;
const int INF=1e5;
int a[maxx],b[maxx];
char aa[maxx],bb[maxx];
int main()
{
    scanf("%s%s",aa+1,bb+1);
    int lena=strlen(aa+1);
    int lenb=strlen(bb+1);
    for(int i=1;i<=lena;i++)
        a[i]=aa[lena-i+1]-'0';
    for(int i=1;i<=lenb;i++)
        b[i]=bb[lenb-i+1]-'0';
    int lenc=max(lena,lenb);
    for(int i=1;i<=lenc;i++)
    {
        a[i]+=b[i];
        a[i+1]+=a[i]/10;
        a[i]%=10;
    }
    int t=INF;
    while(!a[t])
    {
        t--;
        if(t==0)
        {
            puts("0");
            return 0;
        }
    }
    for(int i=t;i>=1;i--)
        printf("%d",a[i]);
    return 0;
}