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

Published: (February 14, 2026 at 08:20 PM EST)
4 min read
Source: Dev.to

Source: Dev.to

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

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. Add the digit from string a (if available).
  2. Add the digit from string b (if available).
  3. 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 append bits to the result as we find them, the final string is built in reverse order. Reversing it yields 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

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;
    }
};

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

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("");
};

Key Takeaways

  • String Manipulation: Processing strings from back to front is essential for many “big number” arithmetic problems.
  • Carry Logic: The sum % base and sum / base pattern works for binary, decimal, hexadecimal, etc.
  • Time Complexity: The solution runs in O(n) time, where n is the length of the longer input string, and uses O(n) additional space for the result.

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.

0 views
Back to Blog

Related posts

Read more »

Did you brush up on your fundamentals?

In the era of AI, theoretical knowledge is more important than ever. Recently, while solving the Reverse Integer problem, I realized the real challenge wasn’t r...