https://leetcode.com/problems/add-binary/
知道二进制加法原理即可,这里只需要知道进位是除数,余数是结果就行。最后不要忽略reg里面的值
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if not a:
return b
elif not b:
return a
tmp_str = ''.join(['0'] * abs(len(a) - len(b)))
if tmp_str:
if len(a) > len(b):
b = tmp_str + b
else:
a = tmp_str + a
reg = 0
res = ''
for i in xrange(len(a) - 1, -1, -1):
tmp = int(a[i]) + int(b[i]) + reg
mod, inc = tmp % 2, tmp / 2
res = str(mod) + res
#print (reg,tmp, mod, inc, res)
reg = inc
if reg != 0:
res = '1' + res
return res
看这个博客。整理的解题思路