Leetcode67: 两个二进制字符串的求和

Leetcode67: Add Binary
具体题目如下:
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”

思路1:先算出a,b求和的十进制数,再将十进制转换为二进制即可,思路简单,代码也比较简洁:

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
       
        s = 0
        for i in range(len(a)):
            if a[i] == '1':
                s += 2**(len(a)-i-1)
        for i in range(len(b)):
            if b[i] == '1':
                s += 2**(len(b)-i-1)
        c = ''
        if s==0:
            return '0'
        while(s):     ##这几行就是把十进制转换为二进制,若想改为其他进制,则把余数改一下就可以了;
            d = s%2
            s = s//2
            c += str(d)
        return c[::-1]

思路2:一开始我对a,b两个字符串的每个字符从低位到高位分别求和,逢2进1,可以AC,但是判断边界条件比较麻烦,具体看代码:

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        
        a = a[::-1]
        b = b[::-1]
        
        length = min(len(a), len(b))
        c = ''
        t = 0
        for i in range(length):
            if int(a[i]) + int(b[i]) + t >= 2:
                c += str(int(a[i]) + int(b[i]) + t-2)
                t = 1
            else:
                c += str(int(a[i]) + int(b[i]) + t)
                t = 0

        i = 0
        if len(a) > len(b):
            while (length + i < len(a) and t + int(a[length + i]) >= 2):
                c += str(t + int(a[length + i]) - 2)
                t = 1
                i += 1
            if length + i == len(a):
                if t ==1:
                    c += '1'
            else:
                c += str(t + int(a[length + i]))
                if length+i+1<len(a):
                    c += a[length + i+1:]
        else:
            while (length + i < len(b) and t + int(b[length + i]) >= 2):
                c += str(t + int(b[length + i]) - 2)
                t = 1
                i += 1
            if length + i == len(b):
                if t ==1:
                    c += '1'
            else:
                c += str(t + int(b[length + i]))
                if length + i + 1 < len(b):
                    c += b[length + i + 1:]
        return c[::-1]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值