Algorithm


Problem Name: 67. Add Binary

problem Link: https://leetcode.com/problems/add-binary/

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"

Constraints:

  • 1 <= a.length, b.length <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

Code Examples

#1 Code Example with C Programming

Code - C Programming


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* addBinary(char* a, char* b) {
    int len_a = strlen(a);
    int len_b = strlen(b);
    int len = (len_a > len_b) ? (len_a) : (len_b);
    char *ans = (char *)malloc(len + 1);
    int i;
    int sum = 0;
    for (i = 0; i  <  len; i++) {
        if (i < len_a && i < len_b) {
            sum += (a[len_a - 1 - i] - '0') + (b[len_b - 1 - i] - '0');
        }
        else if (i  <  len_a) {
            sum += a[len_a - 1 - i] - '0';
        }
        else if (i < len_b) {
            sum += b[len_b - 1 - i] - '0';
        }
        ans[len - i] = sum % 2 + '0';
        sum /= 2;
    }

    ans[len + 1] = '\0';

    if (sum) {
        ans[0] = sum + '0';
        return ans;
    }
    else {
        return ans + 1;
    }
}

int main() {
    /* should be 100 */
    printf("%s\n", addBinary("11", "1"));

    /* should be 0 */
    printf("%s\n", addBinary("0", "0"));

    /* should be 11000 */
    printf("%s\n", addBinary("1011", "1101"));

    return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
a = "11", b = "1"

Output

x
+
cmd
"100"

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    string addBinary(string a, string b) {
        int carry = 0;
        string s = "";
        int i = a.size() - 1;
        int j = b.size() - 1;
        while(i >= 0 || j >= 0 || carry){
            int num1 = i  <  0 ? 0 : a[i] - '0';
            int num2 = j < 0 ? 0 : b[j] - '0';
            int sum = num1 + num2 + carry;
            s.push_back(sum % 2 + '0');
            carry = sum / 2;
            i--;
            j--;
        }
        reverse(s.begin(), s.end());
        return s;
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
a = "1010", b = "1011"

Output

x
+
cmd
"10101"

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
  public String addBinary(String a, String b) {
    StringBuilder sb = new StringBuilder();
    int endIdxA = a.length() - 1;
    int endIdxB = b.length() - 1;
    int carry = 0;
    while (endIdxA >= 0 || endIdxB >= 0 || carry > 0) {
      int value = carry;
      if (endIdxA >= 0) {
        value += Character.getNumericValue(a.charAt(endIdxA--));
      }
      if (endIdxB >= 0) {
        value += Character.getNumericValue(b.charAt(endIdxB--));
      }
      sb.append(value % 2);
      carry = value / 2;
    }
    return sb.reverse().toString();
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
a = "11", b = "1"

Output

x
+
cmd
"100"

#4 Code Example with Javascript Programming

Code - Javascript Programming


const addBinary = function(a, b) {
    let s = ''
    let c = 0
    let i = a.length - 1
    let j = b.length - 1
    while(i >= 0 || j >= 0 || c === 1) {
        c += i >= 0 ? +a[i--] : 0
        c += j >= 0 ? +b[j--] : 0
        s = (c % 2 === 1 ? '1' : '0') + s
        c = Math.floor(c / 2)
    }
    return s
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
a = "11", b = "1"

Output

x
+
cmd
"100"

#5 Code Example with Python Programming

Code - Python Programming


class Solution:
    def addBinary(self, a: str, b: str) -> str:
        return bin(int(a, 2) + int(b, 2))[2:]
Copy The Code & Try With Live Editor

Input

x
+
cmd
a = "11", b = "1"

Output

x
+
cmd
"100"

#6 Code Example with C# Programming

Code - C# Programming


using System.Text;

namespace LeetCode
{
    public class _067_AddBinary
    {
        public string AddBinary(string a, string b)
        {
            var carry = 0;
            var builder = new StringBuilder();

            var aLength = a.Length - 1;
            var bLength = b.Length - 1;

            int aVal, bVal, val;
            while (aLength >= 0 || bLength >= 0)
            {
                aVal = aLength >= 0 ? a[aLength] - '0' : 0;
                bVal = bLength >= 0 ? b[bLength] - '0' : 0;

                val = aVal + bVal + carry;
                builder.Insert(0, val & 1);

                carry = val >> 1;

                aLength--;
                bLength--;
            }

            if (carry >= 1)
            {
                builder.Insert(0, carry);
            }

            return builder.ToString();
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
a = "1010", b = "1011"

Output

x
+
cmd
"10101"
Advertisements

Demonstration


Previous
#66 Leetcode Plus One Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#68 Leetcode Text Justification Solution in C, C++, Java, JavaScript, Python, C# Leetcode