Description
两个string的二进制数相加
Solution
简洁写法
class Solution:
def addBinary(self, a: str, b: str) -> str:
indexa = len(a) - 1
indexb = len(b) - 1
carry = 0
sum = ""
while indexa >= 0 or indexb >= 0:
x = int(a[indexa]) if indexa >= 0 else 0
y = int(b[indexb]) if indexb >= 0 else 0
if x + y + carry >1:
sum = str(x+y+carry-2) + sum
carry = 1
else:
sum = str(x+y+carry) + sum
carry =0
indexa, indexb = indexa - 1, indexb - 1
if carry == 1:
sum = '1' + sum
return sum
class Solution:
def addBinary(self, a: str, b: str) -> str:
carry = 0
sum = 0
res = ''
min_v = min(len(a),len(b))
i = 1
while i <=min_v:
sum = int(a[-i])+int(b[-i])+carry
if sum >1:
carry = 1
sum -=2
else:
carry =0
res = str(sum) + res
i+=1
sum =0
if len(a)> min_v:
j = len(a)-min_v-1
while j >=0:
sum = int(a[j])+carry
if sum < 2:
carry = 0
else:
sum-=2
carry =1
res = str(sum) + res
j-=1
if len(b)>min_v:
j = len(b)-min_v-1
while j >=0:
sum = int(b[j])+carry
if sum < 2:
carry = 0
else:
sum-=2
carry =1
res = str(sum) + res
j-=1
if carry:
res = '1'+res
return res
```