- Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
my thoughts:
1. just follow the rules for binary addition.
my solution:
**********42ms
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if len(a) > len(b):
b, a = a, b
la = len(a)
lb = len(b)
prea = '0'*(lb-la)
a = prea + a
i = lb-1
c = 0
res = []
while i>=0:
if a[i] != b[i]:
n = c+1
c = n/2
res.append(str(n%2))
elif a[i] == '0':
n = c
c = 0
res.append(str(n))
else:
n = c+2
c = 1
res.append(str(n%2))
i -= 1
res.reverse()
r = ''.join(x for x in res)
return r if c==0 else '1'+r
my comments:
from other ppl's solution:
1. bin()
bin(x)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
number = 5
print('The binary equivalent of 5 is:', bin(number))
The binary equivalent of 5 is: 0b101
The prefix 0b represents that the result is a binary string.
use all built in funcs, 29ms:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
num = int(a,2) + int(b,2)
return bin(num)[2:]