DEV Community

Cover image for ⚡ Beginner-Friendly Guide 'Add Binary' - Leetcode Problem 67 (C++, Python, JavaScript)
Om Shree
Om Shree

Posted on

⚡ Beginner-Friendly Guide 'Add Binary' - Leetcode Problem 67 (C++, Python, JavaScript)

Binary addition is the fundamental language of computers, forming the basis for how processors perform every calculation. In this guide, we will break down how to manually simulate the process of adding two bitstrings just like you would with pen and paper.


Problem Summary

You're given:
Two strings, a and b, which represent binary numbers consisting only of the characters '0' and '1'.

Your goal:
Return their sum as a new binary string.


Intuition

The logic follows the same "carry" system we use in decimal addition, but with a base of 2 instead of 10. When we add two digits and the sum exceeds the base, we carry the overflow to the next position on the left.

We process the strings from right to left (from the least significant bit to the most significant bit). For each position:

  1. We add the digit from string a (if available).
  2. We add the digit from string b (if available).
  3. We include any carry from the previous step.
  4. The current bit to store is sum % 2.
  5. The new carry for the next position is sum / 2.

Since we are appending bits to our result string as we find them, the final string will be in reverse order. A quick final reversal gives us the correct answer.


Walkthrough: Understanding the Examples

Example 1: a = "11", b = "1"

  • Step 1: Rightmost digits are 1 and 1. Sum = . Current bit: . Carry: . Result: "0".
  • Step 2: Next digit in a is 1, b is empty. Sum = . Current bit: . Carry: . Result: "00".
  • Step 3: Both strings empty, but carry is 1. Sum = 1. Current bit: . Carry: . Result: "001".
  • Final Step: Reverse "001" to get "100".

Code Blocks

C++

class Solution {
public:
    string addBinary(string a, string b) {
        string result;
        int indexA = a.size() - 1;
        int indexB = b.size() - 1;
        int carry = 0;

        while (indexA >= 0 || indexB >= 0 || carry > 0) {
            if (indexA >= 0) {
                carry += a[indexA] - '0';
                indexA--;
            }

            if (indexB >= 0) {
                carry += b[indexB] - '0';
                indexB--;
            }

            result.push_back((carry % 2) + '0');
            carry /= 2;
        }

        reverse(result.begin(), result.end());
        return result;
    }
};

Enter fullscreen mode Exit fullscreen mode

Python

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        result = []
        index_a = len(a) - 1
        index_b = len(b) - 1
        carry = 0

        while index_a >= 0 or index_b >= 0 or carry > 0:
            if index_a >= 0:
                carry += int(a[index_a])
                index_a -= 1

            if index_b >= 0:
                carry += int(b[index_b])
                index_b -= 1

            result.append(str(carry % 2))
            carry //= 2

        return "".join(result[::-1])

Enter fullscreen mode Exit fullscreen mode

JavaScript

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function(a, b) {
    let result = "";
    let indexA = a.length - 1;
    let indexB = b.length - 1;
    let carry = 0;

    while (indexA >= 0 || indexB >= 0 || carry > 0) {
        let sum = carry;

        if (indexA >= 0) {
            sum += parseInt(a[indexA]);
            indexA--;
        }

        if (indexB >= 0) {
            sum += parseInt(b[indexB]);
            indexB--;
        }

        result += (sum % 2);
        carry = Math.floor(sum / 2);
    }

    return result.split("").reverse().join("");
};

Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • String Manipulation: Learning how to process strings from back to front is a vital skill for many "Big Number" arithmetic problems.
  • Carry Logic: This logic is universal. Whether you are adding binary, decimal, or hexadecimal, the sum % base and sum / base pattern remains the same.
  • Time Complexity: The solution runs in time, where and are the lengths of the strings, making it highly efficient.

Final Thoughts

This problem is a classic for a reason. It tests your ability to handle basic arithmetic logic without relying on built-in language shortcuts (like converting to an integer, which would fail for very long strings due to overflow). Understanding this simulation is essential for roles in low-level systems programming, cryptography, or anywhere where precision with large numbers is required.

Top comments (0)