[Solved] Given two binary strings a and b, return their sum as a binary string.

Question

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.

Python Solution

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        m,n,carry = len(a)-1,len(b)-1,0
        res = []
        while m>=0 or n>=0 or carry!=0:
            if m>=0:
                carry += int(a[m])
                m-=1
            if n>=0:
                carry += int(b[n])
                n-=1
            
            res.append(str(carry%2))
            carry //= 2
            
        return ''.join(reversed(res))
                
Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 514

Leave a Reply

Your email address will not be published. Required fields are marked *