题目:
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
方法一:性能72ms
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
r = 0
for i in range(len(a)):
r += pow(2, i)*int(a[len(a)-i-1])
for i in range(len(b)):
r += pow(2, i)*int(b[len(b)-i-1])
s = '{0:b}'.format(r)
return s
方法二:性能38ms
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a, 2) + int(b,2))[2:]
这里int(a, 2)
表示a是二进制数,将它转换成十进制数。