题目如下:

【leetcode】67. Add Binary

解题思路:首先将较短的输入前面补0,保证a和b长度一样,然后逐位相加再加上进位的值。如果和为3,当前位值为1,进位1;如果为2,当前位值为0,进位为1;否则不进位,当前位值即为和的值。

代码如下:

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        diff = abs(len(a) - len(b))
        if len(a) < len(b):
            a = '0'*diff + a
        elif len(b) < len(a):
            b= '0'*diff + b
        carry = 0
        res = ''
        for i,j in zip(a[::-1],b[::-1]):
            v = int(i) + int(j) + carry
            if v == 3:
                v = 1
                carry = 1
            elif v == 2:
                v = 0
                carry = 1
            else:
                carry = 0
            res = str(v) + res
        if carry > 0:
            res = str(carry) + res
        return res
        

 

相关文章:

  • 2021-08-06
  • 2021-07-01
  • 2022-01-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-28
猜你喜欢
  • 2021-05-03
  • 2021-10-11
  • 2021-09-26
  • 2021-09-08
  • 2021-07-28
  • 2022-03-10
相关资源
相似解决方案