Given two binary strings a
and b
, return their sum as a binary string.
a
and b
are non-empty?
a
and b
.def addBinary(a: str, b: str) -> str:
i, j = len(a) - 1, len(b) - 1
carry = 0
result = []
while i >= 0 or j >= 0 or carry:
# get current digits
x = int(a[i]) if i >= 0 else 0
y = int(b[j]) if j >= 0 else 0
# calculate sum and new carry
total = x + y + carry
carry = total // 2
result.append(str(total % 2))
# move pointers
i -= 1
j -= 1
# reverse result since we've constructed it in reverse order
return ''.join(result[::-1])
# Example usage
a = "1010"
b = "1011"
print(addBinary(a, b)) # Output: "10101"
n
and m
are the lengths of the strings a
and b
respectively. This is because we iterate through both strings once.max(n, m) + 1
in length considering the carry.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?