给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
思路:两种方法,思路详见注释。
1 class Solution(object):
2 def addBinary(self, a, b):
3 """
4 :type a: str
5 :type b: str
6 :rtype: str
7 """
8 return bin(int(a, 2) + int(b, 2))[2:]
9
10 def addBinary2(self, a, b):
11 """
12 :type a: str
13 :type b: str
14 :rtype: str
15 """
16 if a == "0" or b == "0":
17 return a if b == "0" else b
18 # 反转
19 a = a[::-1]
20 b = b[::-1]
21 # 保证a串短,以a串为准进行遍历
22 if len(a) > len(b):
23 a, b = b, a
24 # 两串长度统一
25 while len(a) < len(b):
26 a += "0"
27 # print(a, b)
28 result = ""
29 extra = 0 # 进位
30 for index, num in enumerate(a):
31 ans = (int(num) + int(b[index]) + extra) % 2
32 if int(num) + int(b[index]) + extra > 1:
33 extra = 1
34 else:
35 extra = 0
36 result += str(ans)
37 # 只用判断最高位有进位,不用判断无进位情况
38 if extra == 1:
39 result += "1"
40 return result[::-1]
41
42
43 if __name__ == '__main__':
44 solution = Solution()
45 print(solution.addBinary2(a="1111", b="1"))
46 print(solution.addBinary2(a="10", b="1011"))