题解 | 高精度整数加法

#include <algorithm>

#include <iostream>

using namespace std;

string comp(string s1, string s2) {

    reverse(s1.begin(), s1.end());  //从右往左算

    reverse(s2.begin(), s2.end());

    int n = max(s1.length(), s2.length());

    int carry = 0;

    string res;

    //需要检测到位数较大的数的最高位的下一位,涉及到是否需要加上进位

    for (int i = 0; i <= n; i++) {

        int num1, num2;

        if (i >= s1.length()) num1 = 0;

        else num1 = s1[i] - '0';

        if (i >= s2.length()) num2 = 0;

        else num2 = s2[i] - '0';

        if (i == n && !num1 && !num2 && !carry) break;  //位数相同的时候如果没有进位则不需要继续运算

        int r = num1 + num2 + carry;    //将两个数和进位相加

        if (r > 9) carry = 1;   //超过9则进一位

        else carry = 0;

        res.push_back('0' + (r % 10));  //将每位运算结果计入

    }

    reverse(res.begin(), res.end());    //将结果转到正确的位置

    return res;

}

int main() {

    string s1, s2;

    cin >> s1 >> s2;

    cout << comp(s1, s2);

}

// 64 位输出请用 printf("%lld")

全部评论

相关推荐

迷茫的大四🐶:价格这么低都能满了?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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