洛谷题解 | # P1601 A+B Problem(高精)#

P1601 A+B Problem(高精)

题目描述

高精度加法,相当于 a+b problem,不用考虑负数

输入格式

分两行输入。

输出格式

输出只有一行,代表 的值。

输入输出样例 #1

输入 #1

1
1

输出 #1

2

输入输出样例 #2

输入 #2

1001
9099

输出 #2

10100

说明/提示

的测试数据,

的测试数据,

AC代码

#include <bits/stdc++.h>

using i64 = long long;
using u64 = unsigned long long;
using u32 = unsigned;
using u128 = unsigned __int128;
#define lowbit(x) = ((x) & -(x))
#define rep_0(a, b, c) for (int a = b; a < c; a++)
#define rep_1(a, b, c) for (int a = b; a <= c; a++)
#define per(a, b, c) for (int a = b; a >= c; a--)
using namespace std;
void solve()
{
    string a, b;
    cin >> a >> b;
    vector<int> ans;
    stack<int> ans_a;
    stack<int> ans_b;
    for (int i = 0; a[i]; i++)
    {
        ans_a.push(a[i] - 48);
    }
    for (int i = 0; b[i]; i++)
    {
        ans_b.push(b[i] - 48);
    }
    while (!ans_a.empty() && !ans_b.empty())
    {
        int temp_a, temp_b;
        temp_a = ans_a.top();
        ans_a.pop();
        temp_b = ans_b.top();
        ans_b.pop();
        ans.push_back(temp_a + temp_b);
    }
    if (!ans_a.empty())
    {
        while (!ans_a.empty())
        {
            ans.push_back(ans_a.top());
            ans_a.pop();
        }
    }
    else if (!ans_b.empty())
    {
        while (!ans_b.empty())
        {
            ans.push_back(ans_b.top());
            ans_b.pop();
        }
    }
    for (int p = 0; p < ans.size() - 1; p++)
    {

        if (ans[p] >= 10)
        {
            ans[p + 1] += ans[p] / 10;
            ans[p] = ans[p] % 10;
        }
    }
    while (ans.back() >= 10)
    {
        int num = ans.back();
        ans.push_back(num / 10);
        ans[ans.size() - 2] = num % 10;
    }
    for (int i = ans.size() - 1; i >= 0; i--)
    {
        cout << ans[i];
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t = 1;
    // cin >> t;

    while (t--)
    {
        solve();
    }

    return 0;
}
全部评论

相关推荐

05-23 19:02
吉林大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务