KatInterview

67. Add Binary

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Manual Simulation of Binary Addition

This problem asks us to add two binary strings, which is analogous to adding two decimal numbers by hand. The key is to process the strings from right to left (from least significant bit to most significant bit), keeping track of a carry, just like in elementary school arithmetic.

Solution

Add Binary in Python

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        # Python's int() can handle arbitrarily large integers, so we can convert
        # the binary strings to integers, add them, and convert back to a binary string.
        
        # Convert binary string 'a' to an integer.
        int_a = int(a, 2)
        # Convert binary string 'b' to an integer.
        int_b = int(b, 2)
        
        # Add the two integers.
        sum_int = int_a + int_b
        
        # Convert the sum back to a binary string representation.
        # The bin() function returns a string with a "0b" prefix, which we need to remove.
        # e.g., bin(5) returns '0b101', so we slice from the 2nd index.
        return bin(sum_int)[2:]

Add Binary in Java

class Solution {
    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;

        // Loop until both strings are processed and no carry is left
        while (i >= 0 || j >= 0 || carry > 0) {
            int sum = carry;

            // Add digit from string 'a' if available
            if (i >= 0) {
                sum += a.charAt(i) - '0';
                i--;
            }
            
            // Add digit from string 'b' if available
            if (j >= 0) {
                sum += b.charAt(j) - '0';
                j--;
            }

            // Append the current digit (sum % 2) to the result
            sb.append(sum % 2);
            // Update the carry (sum / 2)
            carry = sum / 2;
        }

        // The result is built in reverse order, so reverse it and convert to String
        return sb.reverse().toString();
    }
}

Add Binary in C++

class Solution {
public:
    string addBinary(string a, string b) {
        string result = "";
        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;

        // Loop until both strings are processed and no carry is left
        while (i >= 0 || j >= 0 || carry > 0) {
            int sum = carry;

            // Add digit from string 'a' if available
            if (i >= 0) {
                sum += a[i] - '0';
                i--;
            }

            // Add digit from string 'b' if available
            if (j >= 0) {
                sum += b[j] - '0';
                j--;
            }

            // The new carry is the sum divided by 2
            carry = sum / 2;
            // The current result digit is the sum modulo 2
            result += to_string(sum % 2);
        }

        // The result is built in reverse order, so we need to reverse it
        reverse(result.begin(), result.end());
        return result;
    }
};

Add Binary in TypeScript

function addBinary(a: string, b: string): string {
    let result = "";
    let i = a.length - 1;
    let j = b.length - 1;
    let carry = 0;

    // Loop until both strings are processed and no carry is left
    while (i >= 0 || j >= 0 || carry > 0) {
        let sum = carry;

        // Add digit from string 'a' if available
        if (i >= 0) {
            sum += a[i] === '1' ? 1 : 0;
            i--;
        }
        
        // Add digit from string 'b' if available
        if (j >= 0) {
            sum += b[j] === '1' ? 1 : 0;
            j--;
        }

        // Prepend the current digit to the result string
        result = (sum % 2) + result;
        // Update the carry
        carry = Math.floor(sum / 2);
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.