Instagram
youtube
Facebook
Twitter

Add Binary Leetcode Solution

In this tutorial, we will solve a leetcode problem Add Binary in python.

Task:

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:
        A = int(a, 2)
        B = int(b, 2)
        
        A = bin(A + B)
        return A[2:]

Steps:

step1: In this problem, we are using the python inbuilt function. 

step2: first we change the type of our string a and b into an integer.

step3: then we convert the sum of these two integers into binary.

step4: after converting it to binary we return the result but after 2 indexes because in binary format it stores as '0b101'.