给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1
和 0
。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
num_a = num_b = 0
for i in range(len(a)-1, -1, -1):
num_a += (2 ** (len(a) -1 - i)) * int(a[i])
for j in range(len(b)-1, -1, -1):
num_b += (2 ** (len(b) -1 - j)) * int(b[j])
result = num_a + num_b
result = str(bin(result))
return result[2:]
方法二:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if len(a) == 0:
return b
if len(b) == 0:
return a
if a[-1] == '1' and b[-1] == '1':
return self.addBinary(self.addBinary(a[0:-1], b[0:-1]), '1') + '0'
if a[-1] == '0' and b[-1] == '0':
return self.addBinary(a[0:-1], b[0:-1]) + '0'
else:
return self.addBinary(a[0:-1], b[0:-1]) + '1'