解析
67. Add Binary
# solution 1 - 写法 1 - myself
# time: O(n)
def addBinary(self, a: str, b: str) -> str:
a, b = a[::-1], b[::-1] # reverse the strings
res = ""
carry = 0
for i in range(max(len(a), len(b))): # time: O(n)
digitA = int(a[i]) if i < len(a) else 0
digitB = int(b[i]) if i < len(b) else 0
curSum = digitA + digitB + carry
char = str(curSum % 2)
carry = curSum // 2
res = char + res # append the new char to the beginning of the res
if carry:
res = "1" + res
return res
# solution 1 - 写法 2 - neetcode
# time: O(n)
def addBinary(self, a: str, b: str) -> str:
a, b = a[::-1], b[::-1] # reverse the strings
res = ""
carry = 0
for i in range(max(len(a), len(b))): # time: O(n)
digitA = ord(a[i]) - ord("0") if i < len(a) else 0
digitB = ord(b[i]) - ord("0") if i < len(b) else 0
curSum = digitA + digitB + carry
char = str(curSum % 2)
carry = curSum // 2
res = char + res # append
if carry:
res = "1" + res
return res
ref
Ref
- `