Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 10^4
- a and b consist only of '0' or '1' characters.
- Each string does not contain leading zeros except for the zero itself.
Solution in python:
class Solution:
def addBinary(self, a: str, b: str) -> str:
lena = len(a)
lenb = len(b)
if lena < lenb:
a = "0" * (lenb - lena) + a
max_len = lenb
else:
b = "0" * (lena - lenb) + b
max_len = lena
c = ""
carry = 0
for i in range(max_len-1, -1, -1):
temp = (int(a[i]) + int(b[i]) + carry)
if temp >= 2:
c = str(temp - 2) + c
carry = 1
else:
c = str(temp) + c
carry = 0
if carry:
c = "1" + c
return c
留言