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

高精度整数加法

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机试真题#
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
点赞 评论 收藏
分享
06-07 17:17
嘉兴学院 教师
心爱的idea:你孩
点赞 评论 收藏
分享
07-02 13:52
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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