Add Binary LeetCode Solution

Last updated on January 19th, 2025 at 10:39 pm

Here, we see an Add Binary LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Math, String

Companies

Facebook

Level of Question

Easy

Add Binary LeetCode Solution

Add Binary LeetCode Solution

1. Problem Statement

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"

2. Coding Pattern Used in Solution

The coding pattern used in the provided code is “Binary Addition Simulation”. The code simulates the process of adding two binary numbers bit by bit, handling carry propagation as in manual binary addition.

3. Code Implementation in Different Languages

3.1 Add Binary C++

class Solution {
public:
    string addBinary(string a, string b) {
        if (a.size() < b.size())
            swap(a, b);
        int i = a.size(), j = b.size();
        while (i--) {
            if (j) a[i] += b[--j] & 1;
            if (a[i] > '1') {
                a[i] -= 2;
                if (i) a[i-1]++; else a = '1' + a;
            }
        }
        return a;        
    }
};

3.2 Add Binary Java

class Solution {
    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int i = a.length() - 1, j = b.length() -1, carry = 0;
        while (i >= 0 || j >= 0) {
            int sum = carry;
            if (j >= 0) sum += b.charAt(j--) - '0';
            if (i >= 0) sum += a.charAt(i--) - '0';
            sb.append(sum % 2);
            carry = sum / 2;
        }
        if (carry != 0) sb.append(carry);
        return sb.reverse().toString();        
    }
}

3.3 Add Binary JavaScript

var addBinary = function(a, b) {
    return (BigInt("0b"+a) + BigInt("0b"+b)).toString(2);    
};    

3.4 Add Binary Python

class Solution(object):
    def addBinary(self, a, b):
        return bin(eval('0b' + a) + eval('0b' + b))[2:]

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(max(n, m))O(max(n, m))
JavaO(max(n, m))O(max(n, m))
JavaScriptO(max(n, m))O(max(n, m))
PythonO(max(n, m))O(max(n, m))
  • In all implementations, the time complexity is determined by the length of the longer string (max(n, m)), where n and m are the lengths of a and b.
  • Each bit is processed once, so the time complexity is O(max(n, m)).
  • In C++ and Java, the space complexity is O(max(n, m)) because the result is stored in a string or StringBuilder of size proportional to the input.
  • In JavaScript and Python, the space complexity is also O(max(n, m)) because the conversion to integers and back to binary involves temporary storage proportional to the input size.
Scroll to Top