String:67. Add Binary

    我写了……一个……很长的代码……唉,我先把短的那个数字补齐,也就是前面缺的那几位补0,然后再加。

    注意

result = char('0' + rx % 2) + result;
    这里面这个强制类型转换是必须必的。不然会报错。

class Solution {
public:
    string addBinary(string a, string b) {
        int x = 0;
        string result = "";
        int an = a.size();
        int bn = b.size();
        if(an > bn)
        {
            for(int i = 0; i < an - bn; ++i)
            {
                b = '0' + b;
            }
        }
        else
        {
            for(int i = 0; i < bn - an; ++i)
            {
                a = '0' + a;
            }
        }
        for(int i = a.size() - 1; i >= 0; --i)
        {
            int rx = (a[i] - '0') + (b[i] - '0') + x;
            if(rx >= 2)
                x = 1;
            else
                x = 0;
            result = char('0' + rx % 2) + result;
        }
        if(x == 1)
            result = '1' + result;
        return result;
    }
};
    看看别人写的,再看看我写的……简直是垃圾。

class Solution {
public:
    string addBinary(string a, string b) {
        string s = "";
        
        int c = 0, i = a.size() - 1, j = b.size() - 1;
        while(i >= 0 || j >= 0 || c == 1)
        {
            c += i >= 0 ? a[i --] - '0' : 0;
            c += j >= 0 ? b[j --] - '0' : 0;
            s = char(c % 2 + '0') + s;
            c /= 2;
        }
        
        return s;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值