给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1
和 0
。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
代码:
#add-binary
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
s = str(int(a) + int(b))
l = [int(x) for x in s]
for i in range(len(l))[::-1]:
if l[i] > 1:
l[i] %= 2
if i != 0:
l[i - 1] += 1
else:
l.insert(0,1)
res = ''
for x in l:
res += str(x)
return res
大神写法:利用python的内置函数
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return str(bin(int(a,2)+int(b,2)))[2:]
链接: