Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
思路:
把字符串表示成二进制数字,然后相加,再转换为二进制表示为字符串。
引申:一个问题,在Python中,如何将一个字符串转换为相应的二进制串(01形式表示),并且能够将这个二进制串再转换回原来的字符串
>>> bin(int('256', 10))
'0b100000000'
>>> str(int('0b100000000', 2))
'256'
一开始使用replace,发现效率很低,后来换为了[2:]之后就快了很多。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
# return bin(int(str(int(a, 2) + int(b, 2)), 10)).replace('0b', '')
return bin(int(str(int(a, 2) + int(b, 2)), 10))[2:]
if __name__ == '__main__':
sol = Solution()
a = '11'
b = '1'
print sol.addBinary(a, b)
a = '0'
b = '0'
print sol.addBinary(a, b)