python代码
方法一:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
sum_a,sum_b = 0,0
reverse_a = a[::-1]
reverse_b = b[::-1]
for i in range(len(reverse_a)):
sum_a = sum_a + int(reverse_a[i])*(2**i)
for i in range(len(reverse_b)):
sum_b = sum_b + int(reverse_b[i])*(2**i)
sum = sum_a +sum_b
sum = bin(sum)[2::]
return sum
方法二:
‘{0:b}’ b代表二进制
D(decimal)表示这个数是十进制
B(binary)表示这个数是二进制
O(octor)表示这个数是八进制
H(hex)表示这个数是十六进制
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return '{0:b}'.format(int(a, 2) + int(b, 2))
方法三:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
ans,extra = '',0
i,j = len(a)-1,len(b)-1
while i>=0 or j >=0:
if i >=0:
extra += ord(a[i])-ord('0')
if j >=0:
extra += ord(b[j])-ord('0')
ans += str(extra % 2)
extra //= 2
i,j = i-1,j-1
if extra == 1:
ans += '1'
return ans[::-1]