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

Machine Learning Projects

Table of Contents

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))
                

Leave a Comment

Your email address will not be published.