题解 | 【模板】高精度加法

【模板】高精度加法

https://www.nowcoder.com/practice/c26e34baf994453eae63fe05d39009e3

直接在字符串上操作即可。倒序方便进位。

#include <algorithm>
#include <iostream>
using namespace std;

string a;
string b;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> a >> b;
    reverse(a.begin(), a.end());
    reverse(b.begin(), b.end());
    for (int i = 0; i < a.size() && i < b.size(); i++) {
        if (i == a.size()) {
            a += '0';
        }
        a[i] += i == b.size() ? 0 : b[i] - '0';
        if (a[i] > '0' + 9) {
            a[i] -= 10;
            if (i + 1 == a.size()) {
                a += '1';
            } else {
                a[i + 1]++;
            }
        }
    }
    reverse(a.begin(), a.end());
    cout << a;
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

钱嘛数字而已:拖拉机被发明出来之后,就不需要农民了吗?农民还是需要的,但不需要这么多了,另外对农民的要求也变高了,需要会开拖拉机。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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