https://leetcode.com/problems/add-binary/description/
将两个字符串表示的二进制数相加,结果以字符串形式返回
思路:从最低位开始,逐位相加。每次用一个累加器c进行十进制
加法,因为单纯计算二进制会丢失进位信息,而用十进制则不一样:0+0 = 0,0+1 = 1, 1+1 = 2,这样就带有更丰富的信息,如1+1在二进制中发生了进位,用整数除法除2可获得进位信息。
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
i, j = len(a)-1, len(b)-1 #i,j分别用于迭代a,b串
c = 0 #记录本轮加法结果
res = ''
while i >= 0 or j >= 0 or c > 0: #当a,b串有一个未结束,或者仍有进位
if i >= 0:
c += int(a[i]) #累加
if j >= 0:
c += int(b[j]) #累加
res = str(c % 2) + res #将该位结果转成字符,并写入结果左侧
c //= 2 #进位信息
i -= 1 #指针前移
j -= 1
return res