[leetcode] 67. Add Binary

556 篇文章 2 订阅
441 篇文章 0 订阅

Description

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

The input strings are both non-empty and contains only characters 1 or 0.
Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

分析一

  • 思路很简单,对a,b从后往前遍历进行加法运算,然后把结果存入栈中,以栈出来的顺序拼接成字符串就是结果了。

C++实现1

class Solution {
public:
    string addBinary(string a, string b) {
        stack<int> s;
        int s1=a.length();
        int s2=b.length();
        int i=s1-1;
        int j=s2-1;
        int carry=0;
        while(i>=0||j>=0||carry>0){
            int n1=i>=0 ? a[i--]-'0':0;
            int n2=j>=0 ? b[j--]-'0':0;
            int c=carry+n1+n2;
            s.push(c%2);
            carry=c/2;
        }
        string res="";
        while(!s.empty()){
            res+=s.top()+'0';
            s.pop();
        }
        return res;
    }
};

C++实现2

  • 首先要用0把两个字符串补齐,补齐之后,从最后一位进行二进制的加法运算。

代码二

class Solution {
public:
    string addBinary(string a, string b) {
        int a1_len=a.length()-1;
        int b1_len=b.length()-1;
        while(a.length()>b.length()){
            b='0'+b;
        }
        while(b.length()>a.length()){
            a='0'+a;
        }
        string s1;
        char flag='0';
        for(int i=a.length()-1;i>=0;i--){
            int ch=a[i]-'0'+b[i]-'0'+flag-'0';
            if(ch==3){
                s1='1'+s1;
                flag='1';
            }else if(ch==2){
                s1='0'+s1;
                flag='1';
            }else{
                char c=ch+'0';
                s1=c+s1;
                flag='0';
            }
        }
        if(flag=='1'){
            s1='1'+s1;
        }
        return s1;
    }
};

Python实现

思路很粗暴,直接转换成二进制做处理即可。

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        x, y = int(a,2), int(b,2)
        while y:
            ans = x^y
            carry = (x&y)<<1
            x,y = ans, carry
        return bin(x)[2:]

下面是一个标准模板的遍历做法:

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        m = len(a)
        n = len(b)
        i = m-1
        j = n-1
        carry = 0
        res = ""
        while i>=0 or j>=0:
            if i>=0:
                carry+=int(a[i])
                i-=1
            if j>=0:
                carry+=int(b[j])
                j-=1
            res = str(carry%2)+res
            carry = carry//2
        if carry:
            res=str(carry)+res
        return res

参考文献

[编程题]add-binary

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值