LeetCode 67. Add Binary

本文介绍了一种使用C++实现的二进制字符串加法的方法。通过模拟二进制加法的过程,该方法能够处理不同长度的二进制字符串,并返回它们相加后的结果。

描述

string类型的二进制数的加法

解决

模拟


class Solution {
public:
    string addBinary(string a, string b){
        int posA = a.size();
        int posB = b.size();
        //string res = "";
        int minLenth = (posA >= posB) ? posB : posA;
       // cout << minLenth << endl;
       // minLenth;
        int maxLenth = (posA >= posB) ? posA : posB;
       // maxLenth;
        string res(maxLenth + 1, '0');
        int carry = 0;
        --posA, --posB;
        while (posA >= 0 || posB >= 0 || carry >= 1){
            int tmpA = posA >= 0 ? a[posA] - '0' : 0;
            int tmpB = posB >= 0 ? b[posB] - '0' : 0;
            int tmpSum = tmpA + tmpB + carry;
            carry = tmpSum / 2;
           // cout << res[maxLenth] << endl;
           // tmpSum;
            res[maxLenth] = '0' + (tmpSum % 2);
            //cout << "aa" << res[maxLenth] << endl;
            --posA, --posB, --maxLenth;
        //    carry = 0;
        }
        string::iterator it = res.begin();
        while (*it == '0'){
            ++it;
        }
        //cout << res[0] << endl;
        //cout << "zz" << res.size() << endl;
        return it == res.end() ? "0" : string(it, res.end());
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值