動機
加加加
Problem
Given two binary strings a
and b
, return their sum as a binary string.
Example 1:
Input: a = 11, b = 1Output: 100
Example 2:
Input: a = 1010, b = 1011Output: 10101
Constraints:
1 <= a.length, b.length <= 104
a
andb
consist only of'0'
or'1'
characters.- Each string does not contain leading zeros except for the zero itself.
Sol
就之前在2用的方法
class Solution:
def addBinary(self, a: str, b: str) -> str:
a,b = [int(n) for n in list(a[::-1])], [int(n) for n in list(b[::-1])]
ret,carry = [], 0
while a or b:
if a and b:
tmp = a[0]+b[0]+carry
ret.append(tmp%2)
carry = tmp//2
a,b = a[1:],b[1:]
elif a:
tmp = a[0]+carry
ret.append(tmp%2)
carry = tmp//2
a = a[1:]
else:
tmp = b[0]+carry
ret.append(tmp%2)
carry = tmp//2
b = b[1:]
if carry:
ret.append(carry)
return ''.join([str(n) for n in ret[::-1]])