leetCode(52):Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"

Return "100".

题目并不复杂,以下是我的程序,后面是别人的程序,瞬间low了好大一截!


冗长!!!!!!!
class Solution {
public:
    string addBinary(string a, string b) {
        string result;
        bool more=false;
        int i,j;
        for(i=a.size()-1,j=b.size()-1;i>=0 && j>=0;i--,j--)
        {
            if(!more)
            {
                if(a[i]=='0' && b[j]=='0')
                {
                    result.push_back('0');
                }
                else if((a[i]=='0' && b[j]=='1') || (a[i]=='1' && b[j]=='0'))
                {
                    result.push_back('1');
                }
                else
                {
                    result.push_back('0');
                    more=true;
                }
            }
            else
            {
                if(a[i]=='0' && b[j]=='0')
                {
                    result.push_back('1');
                    more=false;
                }
                else if((a[i]=='0' && b[j]=='1') || (a[i]=='1' && b[j]=='0'))
                {
                    result.push_back('0');
                    more=true;
                }
                else
                {
                    result.push_back('1');
                    more=true;
                }
            }
        }
        
        string c=(i>=0?a:b);
        int k=(i>=0?i:j);
        for(;k>=0;k--)
        {
            if(!more)
            {
                result.push_back(c[k]);   
            }
            else
            {
                if(c[k]=='0')
                {
                    result.push_back('1');
                    more=false;
                }
                else
                {
                    result.push_back('0');
                    more=true;
                }
            }
        }
        
        if(more)
            result.push_back('1');
            
        reverse(result.begin(),result.end());
        return result;
    }
};


大神的


循环判断自增一体,简洁有力!!!!!差距啊
struct Solution {
    string addBinary(string a, string b) {
        if (a.size() < b.size())
            swap(a, b);//直接保存在a中,不用辅助空间
        int i = a.size(), j = b.size();
        while (i--) {
            if (j) a[i] += b[--j] & 1;//‘0’& 1为0 ,‘1’& 1为1
            if (a[i] > '1') {//如果需要进位
                a[i] -= 2;//进位后的字符
                if (i)
                    a[i-1]++; //进位
                else 
                    a = '1' + a;//增加一位
            }
        }
        return a;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值