题解 | #高精度整数加法#

高精度整数加法

https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6

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

int main() {
    string add1, add2;
    cin >> add1 >> add2;

    int N1 = add1.size();
    int N2 = add2.size();
    int l, k;
    bool morel;
    if (N1 > N2) {
        l = N2;
        k = N1;
        morel = true;
    } else {
        l = N1;
        k = N2;
        morel = false;
    }
    int bs;
    string res;
    int advance = 0;
    for (int i = 1; i <= l; i++) {
        bs = add1[N1 - i] - '0' + add2[N2 - i] - '0' + advance;
        if (bs >= 10) {
            res += to_string(bs % 10);
            advance = 1;
        } else {
            res += to_string(bs);
            advance = 0;
        }
    }
    for (int i = l + 1; i <= k; i++) {
        if (morel) {
            bs = add1[N1 - i] - '0' + advance;
            if (bs >= 10) {
                res += to_string(bs % 10);
                advance = 1;
            } else {
                res += to_string(bs);
                advance = 0;
            }
        } else {
            bs = add2[N2 - i] - '0' + advance;
            if (bs >= 10) {
                res += to_string(bs % 10);
                advance = 1;
            } else {
                res += to_string(bs);
                advance = 0;
            }
        }
    }
    if (advance == 1) res += '1';
    reverse(res.begin(), res.end());
    cout << res;
}
// 64 位输出请用 printf("%lld")

模拟

#华为OD机试真题#
全部评论

相关推荐

Natrium_:这时间我以为飞机票
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务