Add Binary LeetCode Solution

Last updated on October 9th, 2024 at 10:03 pm

Here, We see Add Binary LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Math, String

Companies

Facebook

Level of Question

Easy

Add Binary LeetCode Solution

Add Binary LeetCode Solution

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"

1. Add Binary Leetcode Solution 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;        
    }
};

2. Add Binary Leetcode Solution 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. Add Binary Leetcode Solution JavaScript

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

4. Add Binary Leetcode Solution Python

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