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

高精度整数加法

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

定义一个进位变量,两个字符串从个位开始每一位逐位相加并和进位相加,如果结果大于10,则进位为1,否则进位为0。某个字符串加完所有位之后,就用进位和另一个字符串进行运算,加完之后如果进位为1,则在最高位加1。

#include <iostream>
using namespace std;

int main() {
    string s1, s2;
    cin >> s1 >> s2;
    int count1 = s1.length() - 1;
    int count2 = s2.length() - 1;
    int high = 0;
    string ans;
    while (count1 >= 0 && count2 >= 0) {
        ans = to_string((s1.at(count1) + s2.at(count2) - 2 * '0' + high) % 10) + ans;
        high = (s1.at(count1) + s2.at(count2) - 2 * '0' + high) / 10;
        count1--;
        count2--;
    }
    if (count1 > 0) {
        while (count1 >= 0) {
            ans = to_string((s1.at(count1) - '0' + high) % 10) + ans;
            high = (s1.at(count1) - '0' + high) / 10;
            count1--;
        }
    } else if (count2 > 0) {
        while (count2 >= 0) {
            ans = to_string((s2.at(count2) - '0' + high) % 10) + ans;
            high = (s2.at(count2) - '0' + high) / 10;
            count2--;
        }
    }
    if (high > 0) {
        ans = to_string(high) + ans;
    }
    cout << ans;
    return 0;
}
// 64 位输出请用 printf("%lld")

中等(算法题解) 文章被收录于专栏

中等难度题目

全部评论

相关推荐

12-02 20:08
已编辑
门头沟学院 后端工程师
notbeentak...:孩子,说实话,选择很重要,可能你换一个方向会好很多,但是现在时间不太够了,除非准备春招
点赞 评论 收藏
分享
八极星:有什么不能问的,(/_\),这又不是多珍贵的机会,你有什么可失去的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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