leetcode67. 二进制求和 🌟

题目:

  给定两个二进制字符串,返回他们的和(用二进制表示)。

  输入为非空字符串且只包含数字 1 和 0。

示例 1:

  输入: a = "11", b = "1"
  输出: "100"
示例 2:

  输入: a = "1010", b = "1011"
  输出: "10101"

来源:力扣(LeetCode)

解答:

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        return bin(int(a, 2) + int(b, 2))[2:]
View Code

 

class Solution:
     """
         作者:QQqun902025048
         链接:https://leetcode-cn.com/problems/two-sum/solution/python-1xing-nei-zhi-han-shu-fei-nei-zhi-jie-fa-by/
     """
     def addBinary(self, a: str, b: str) -> str:
         r, p = '', 0
         d = len(b) - len(a)
         a = '0' * d + a
         b = '0' * -d + b   # '0' * -d = ''
         for i, j in zip(a[::-1], b[::-1]):
             s = int(i) + int(j) + p
             r = str(s % 2) + r
             p = s // 2
         return '1' + r if p else r
View Code

 

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        _sum = ''
        c = 0
        d = len(a) - len(b)
        a = '0' * -d + a
        b = '0' * d + b
        for i in range(len(a) - 1, -1, -1):
            s = int(a[i]) + int(b[i]) + c
            if s == 2:
                s = 0
                c = 1
            elif s == 3:
                s = 1
                c = 1
            else:
                c = 0
            _sum = str(s) + _sum
        
        if c == 1:
            _sum = '1' + _sum
        return _sum
View Code

 

posted @ 2019-07-12 22:47  catyuang  阅读(138)  评论(0编辑  收藏  举报