Add Binary

String Math

Problem

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

For example:

Input: a = "11", b = "1"
Output: "100"
Input: a = "1010", b = "1011"
Output: "10101"

Thought Process

  • Notice how when we add two digits, there can potentially be a digit that carries over (i.e., adding 1 + 1 = 0 but this translates to a carried 1)

  • We will have two pointers pointing at the end of both strings to simulate adding them together

  • Since we are appending to a string for our final output, we have to reverse this string at the end to get the corret number (since appending to the string adds to the element to the back)

Solution

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        res = ""
        i = len(a) - 1
        j = len(b) - 1
        carry = 0
        while(i>= 0 or j >= 0):
            numSum = carry
            if i >= 0:
                numSum+=int(a[i]) #you can do either one to get the integer representation
            if j >= 0:
                numSum+=ord(b[j]) - ord('0')
            i-=1
            j-=1
            if numSum > 1:
                carry = 1
            else:
                carry = 0 
            res+=str(numSum%2) #mod by 2 in case we have 1+1+1
        
        if carry != 0: #if we have a carry left over
            res+=str(carry)
        return res[::-1]

Key Facts

  • Two pointers to traverse through both integer strings

  • After adding the two numbers, we need to check if the sum is greater than 1, if so then carry = 1

  • After the additon, we need to mod by 2 and append this to our result.

    • Mod by 2 because we can potentially have 1+1+1 which results in 3 but would translate to a 1.

Time Complexity

Last updated