跳到正文

题解

题解:P1001 A+B Problem

_Ec__yt_qwq_约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟
获赞
1
题目
P1001

版本

仅有当前版本

这还不大炮打蚊子吗。

部分解

你说得对,这是一个暴力解!

你说得对,但是我们需要逐步讲解!

你说得对,首先是头文件,新学 OI 的萌新一定要知道。

你说得对,比赛尽量不用万能头文件 #include<bits/stdc++.h>,不过你说得对,平时刷题可以避免“火车头”的出现。

你说得对,用 cin cout 的 OIer 们一定要加上 using namespace std;。你说得对,不然会编译错误!

你说得对,这是主函数 int main()。你说得对,当今后使用 #define int long long 时,可以将 int 换成 signed!

你说得对,这就是主框架的部分了:

C++
#include<bits/stdc++.h>
using namespace std;
int main(){
    return 0;//终止主函数并返回0,平时可以不用写,比赛时必须加上哦
}

你说得对,接下来就是程序部分了:

你说得对,像这样定义一个 int 类型的变量 aa:int a;

你说得对,再操作一遍,定义一个 bb(你说得对,不可以重复使用变量名哦):int a;

你说得对,利用 cin 输入它们:cin>>a>>b;

你说得对,最后再利用 cout 输出它们的和 cout<<a+b; 就可以了!

你说得对,但这效率太差了。

正解

你说得对,我们需要用到高精度加法!

你说得对,我们要定义三个数组!

你说得对,我们要将这两个使用字符串的形式读入!

你说得对,我们要考虑负数,要将加法变成减法!

你说得对,我们要将他们转换成数组!你说得对,还需要再反转过来!

你说得对,我们要按照竖式的形式相加!

你说得对,我们要将进位存储并加到对应位上!

你说得对,最后再反转过来并输出就成功了!

C++
#include <bits/stdc++.h>
using namespace std;
char ch[10010];
int a[10010], b[10010], la, lb;
int main()
{
    scanf("%s", ch + 1);
    if (ch[1] == '-')
    {
        la = strlen(ch + 1) - 1;
        for (int i = 2; i <= la + 1; ++i)
            a[la + 1 - i + 1] = -(ch[i] - '0');
    }
    else
    {
        la = strlen(ch + 1);
        for (int i = 1; i <= la; ++i)
            a[la - i + 1] = ch[i] - '0';
    }

    scanf("%s", ch + 1);
    if (ch[1] == '-')
    {
        lb = strlen(ch + 1) - 1;
        for (int i = 2; i <= lb + 1; ++i)
            b[lb + 1 - i + 1] = -(ch[i] - '0');
    }
    else
    {
        lb = strlen(ch + 1);
        for (int i = 1; i <= lb; ++i)
            b[lb - i + 1] = ch[i] - '0';
    }
    la = max(la, lb) + 1;
    for (int i = 1; i < la; ++i)
        a[i] += b[i];
    for (int i = 1; i < la; ++i)
    {
        a[i + 1] += a[i] / 10;
        a[i] %= 10;
        if (a[i] < 0)
        {
            a[i] += 10;
            --a[i + 1];
        }
    }
    while (la > 1 && a[la] == 0)
        --la;
    if (a[la] < 0)
    {
        printf("-");
        for (int i = 1; i <= la; ++i)
            a[i] = -a[i];
        for (int i = 1; i < la; ++i)
        {
            if (a[i] < 0)
            {
                a[i] += 10;
                --a[i + 1];
            }
        }
        while (la > 1 && a[la] == 0)
            --la;
        for (int i = la; i >= 1; --i)
            printf("%d", a[i]);
    }
    else
        for (int i = la; i >= 1; --i)
            printf("%d", a[i]);
    printf("\n");
    return 0;
}
原文