Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
解题思路:
使用Python的内置函数 .zfill(总长度) 将 a、b两字符串补为相等的字符串,然后从后往前相加。
Python实现:
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
ans = ''
alen = len(a); blen = len(b)
if alen < blen: # 如果两字符串不相等,则较短的字符串前面补0到与较长的字符串等长
a = a.zfill(blen)
elif alen > blen:
b = b.zfill(alen)
bit = 0
i = len(a) - 1
while i >= 0:
if int(a[i]) + int(b[i]) + bit == 0:
ans = '0' + ans
bit = 0
elif int(a[i]) + int(b[i]) + bit == 1:
ans = '1' + ans
bit = 0
elif int(a[i]) + int(b[i]) + bit == 2: #产生进位
ans = '0' + ans
bit = 1
else: #产生进位
ans = '1' + ans
bit = 1
i -= 1
if bit == 1: # 如果最后还有进位
ans = '1' + ans
return ans
a = "11"
b = "111"
c = Solution()
print(c.addBinary(a,b)) # '1010'