题解 | a+b

a+b

https://www.nowcoder.com/practice/4c39c984ea3848b48e111b8e71ec1dd4

本题与火星A+B类似,都是用字符串模拟加法

#include <iostream>
#include <string>
#include <cmath>
#include <vector>
using namespace std;

int main() {
    string s1, s2;
    while (cin >> s1 >> s2) {
        // 在高位补0对齐位数
        while (s1.size() < s2.size()) {
            s1.insert(0, 1, '0');
        }
        while (s1.size() > s2.size()) {
            s2.insert(0, 1, '0');
        }

        vector<int> ans;
        bool carry = false;
        // 从低位开始十进制加法
        for (int i = s1.size() - 1, j = s2.size() - 1; i >= 0 && j >= 0; --i, --j) {
            int sum = s1[i] - '0' + s2[j] - '0';
            if (carry) sum += 1;
            if (sum >= 10) {
                ans.push_back(sum - 10);
                carry = true;
                continue;
            }
            ans.push_back(sum);
            carry = false;
        }

        // 如果最高位仍有进位,加到结果中
        if (carry) ans.push_back(1);

        // 输出结果
        for (auto it = ans.rbegin(); it != ans.rend(); it++) {
            cout << *it;
        }
        cout << endl;
    }
    return 0;
}
全部评论

相关推荐

头像
04-17 09:29
已编辑
湖南农业大学 后端
睡姿决定发型丫:本硕末9也是0offer,简历挂了挺多,只有淘天 美团 中兴给了面试机会,淘天二面挂,美团一面kpi面,中兴一面感觉也大概率kpi(虽然国企,但一面0技术纯聊天有点离谱吧)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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