【模拟】二进制求和

#include <iostream>
using namespace std;
string addBinary(string a, string b){
    string res;
    int carry = 0;  // 进位
    int i = a.size() - 1;
    int j = b.size() - 1;
    while(i >= 0 || j >= 0 || carry != 0){
        int A = i >= 0 ? a[i--] - '0' : 0;
        int B = i >= 0 ? b[j--] - '0' : 0;
        int sum = A + B + carry;
        carry = sum / 2;
        res = to_string(sum % 2) + res;
    }
    return res;
}
int main(){
    string a,b;
    cin >> a >> b;
    cout << addBinary(a, b) << endl;
}
© 版权声明
THE END
点赞14 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容

【C++】小竹的C++学习笔记分享 | 78篇体系化文档×4.7 万字(PDF 可下载) - AI科研 编程 读书笔记 - 小竹の笔记本
订阅本站更新 - AI科研 编程 读书笔记 - 小竹の笔记本
【日常】2025年度总结(重磅手敲8K字) - AI科研 编程 读书笔记 - 小竹の笔记本