LeetCode 之 Add Binary

本文介绍了一种算法,用于解决两个二进制字符串相加的问题,并提供了详细的代码实现及优化过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

Return "100".

这道题并不复杂,需要注意的是要从后往前遍历a,b求和,同时要有一个进位项,对各种情况都要分析到:

string addBinary(string a, string b) {
        string ans;
        if(a.size()==0) return b;
        if(b.size()==0) return a;
        int plus=0;
        int a1=a.size()-1;
        int b1=b.size()-1;
        while(a1!=-1||b1!=-1){
            if(a1!=-1&&b1!=-1){
                if(a[a1]=='1'&&b[b1]=='1'&&plus==1) { ans.append("1");plus=1;}
                else if(a[a1]=='1'&&b[b1]=='1'&&plus==0) { ans.append("0");plus=1;}
                else if(a[a1]=='0'&&b[b1]=='0'&&plus==1) { ans.append("1");plus=0;}
                else if(a[a1]=='0'&&b[b1]=='0'&&plus==0) { ans.append("0");plus=0;}
                else if(plus==0) { ans.append("1");plus=0;}
                else { ans.append("0");plus=1; }
                a1--;b1--;
            }else if(a1==-1&&b1!=-1){
                if(b[b1]=='1'&&plus==1) { ans.append("0");plus=1;}
                else if(b[b1]=='0'&&plus==0) { ans.append("0");plus=0;}
                else { ans.append("1");plus=0;}
                b1--;
            }else if(a1!=-1&&b1==-1){
                if(a[a1]=='1'&&plus==1) { ans.append("0");plus=1;}
                else if(a[a1]=='0'&&plus==0) { ans.append("0");plus=0;}
                else { ans.append("1");plus=0;}
                a1--;
            }
        }
        if(plus==1) ans.append("1");
        reverse ( ans.begin(), ans.end () );
        return ans;
    }

可以看到比较繁琐,进行优化,结果如下:

string addBinary(string a, string b) {
        string ans;
        if(a.size()==0) return b;
        if(b.size()==0) return a;
        int plus=0;
        int a1=a.size()-1;
        int b1=b.size()-1;
        while(a1!=-1||b1!=-1){
            if(a1!=-1&&b1!=-1){
                int i=a[a1]-'0'+b[b1]-'0'+plus;
                ans.append(std::to_string(i%2));plus=i/2;
                a1--;b1--;
            }else if(a1==-1&&b1!=-1){
                int i=b[b1]-'0'+plus;
                ans.append(std::to_string(i%2));plus=i/2;
                b1--;
            }else if(a1!=-1&&b1==-1){
                int i=a[a1]-'0'+plus;
                ans.append(std::to_string(i%2));plus=i/2;
                a1--;
            }
        }
        if(plus==1) ans.append("1");
        reverse(ans.begin(),ans.end());
        return ans;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值