LeetCode-Add Binary

MaheswaraReddy
2 min readJan 3, 2023

--

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 <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

Solution

class Solution:

def addBinary(self, a: str, b: str) -> str:

lena = len(a)

lenb = len(b)

temp = ‘’

result = []

carry = 0

if lena > lenb:

for j in range(lena-lenb):

temp = temp + ‘0’

b = temp + b

elif lena < lenb:

for j in range(lenb-lena):

temp = temp + ‘0’

a = temp + a

else:

temp = “”

a = a[::-1]

b = b[::-1]

for ij in range(len(a)):

if a[ij] == ‘1’ and b[ij] == ‘1’ and carry == 1:

result.insert(ij, 1)

carry = 1

elif a[ij] == ‘1’ and b[ij] == ‘1’ and carry == 0:

result.insert(ij, 0)

carry = 1

elif a[ij] == ‘1’ and b[ij] == ‘0’ and carry == 1:

result.insert(ij, 0)

carry = 1

elif a[ij] == ‘1’ and b[ij] == ‘0’ and carry == 0:

result.insert(ij, 1)

carry = 0

elif a[ij] == ‘0’ and b[ij] == ‘1’ and carry == 1:

result.insert(ij, 0)

carry = 1

elif a[ij] == ‘0’ and b[ij] == ‘1’ and carry == 0:

result.insert(ij, 1)

carry = 0

elif a[ij] == ‘0’ and b[ij] == ‘0’ and carry == 1:

result.insert(ij, 1)

carry = 0

elif a[ij] == ‘0’ and b[ij] == ‘0’ and carry == 0:

result.insert(ij, 0)

carry = 0

if carry == 1:

result.insert(len(result), 1)

result = ‘’.join([str(elem) for elem in result])

result = result[::-1]

return result

Thanks for reading, I hope it will be useful for 1 person in the universe. Happy for your support.

--

--

No responses yet