LeetCode 0067

67. Add Binary

原题链接

我的思路:

直接两个字符串按尾对齐,然后模拟加法就好了。只要细心一点应该是没有问题的。

我的代码:

class Solution {
public:
    string addBinary(string a, string b) {
        string res = "";
        int la = a.size();
        int lb = b.size();
        // let la >= lb
        if(la < lb) {
            string t = a;
            a = b;
            b = t;
        } 
        la = a.size();
        lb = b.size();
        int ia;
        int ib;
        int carry = 0;
        for(int i = lb - 1; i >= 0; i--) {
            ia = a[la - lb + i] - '0';
            ib = b[i] - '0';
            if(ia + ib + carry > 1) {
                res = (char)(ia + ib + carry - 2 + '0') + res;
                carry = 1;
            } else {
                res = (char)(ia + ib + carry + '0') + res;
                carry = 0;
            }
        }
        for(int i = la - lb - 1; i >= 0; i--) {
            ia = a[i] - '0';
            if(ia + carry > 1) {
                res = (char)(ia + carry - 2 + '0') + res;
                carry = 1;
            } else {
                res = (char)(ia + carry + '0') + res;
                carry = 0;
            }
        }
        if(carry) {
            res = "1" + res; 
        }
        return res;
    }
};

最快解法的代码:

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;
    }
};

首先思路是差不多的,其次,这份代码比我的要简洁一些,因为这份代码很好地将三种情况结合在了一起。在我的代码中,三种情况分别是第1个for循环,第2个for循环,以及最后一个if。但是运行速度好像差的有点多,我尝试着把输出语句去掉,然后就和最快解法一样快了。。。。。。所以说,输出很花费时间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值