Code Logo

Add Binary Strings

Published at25 Jul 2026
Medium 1 views
Like0

Given two strings representing binary numbers (containing only '0' and '1'), add them and return the sum as a binary string.

For example, adding "11" (3) and "1" (1) gives "100" (4). "1010" + "1011" = "10101". "0" + "0" = "0".

Binary addition is a fundamental computer science concept. It teaches carry propagation, digit-by-digit addition from right to left, and the base-2 number system. The algorithm simulates how CPUs perform addition at the hardware level.

The solution iterates from the rightmost digit of both strings, adding corresponding digits along with any carry. The sum digit is sum % 2, and the new carry is sum // 2. After processing all digits, if a carry remains, prepend '1'.

Edge cases include both strings being "0" (return "0"), strings of different lengths (pad the shorter one with leading zeros), and a final carry that adds an extra digit to the result.

Example Input & Output

Example 1
Input
"1010","1011"
Output
"10101"
Explanation

1010 + 1011 = 10101

Example 2
Input
"0","0"
Output
"0"
Explanation

Zero sum

Example 3
Input
"1","0"
Output
"1"
Explanation

1 + 0 = 1

Example 4
Input
"11","1"
Output
"100"
Explanation

11 + 1 = 100

Example 5
Input
"111","111"
Output
"1110"
Explanation

111 + 111 = 1110

Algorithm Flow

Recommendation Algorithm Flow for Add Binary Strings

Solution Approach

Add binary digits from right to left, tracking the carry and building the result.

function addBinary(a, b)
  i = length(a) - 1, j = length(b) - 1, carry = 0, result = ""
  while i >= 0 or j >= 0 or carry > 0
    sum = carry
    if i >= 0 then sum = sum + int(a[i]); i = i - 1
    if j >= 0 then sum = sum + int(b[j]); j = j - 1
    result = string(sum % 2) + result
    carry = sum / 2
  return result

Start from the last index of each string. While digits remain or carry exists: add the current digits from both strings (if available) plus the carry. Prepend sum % 2 to the result. Update carry to sum // 2. Return the built string.

Time complexity is O(max(n, m)), space complexity is O(max(n, m)) for the result.

Best Answers

java
class Solution {
    public String solution(String a, String b) {
        int i=a.length()-1,j=b.length()-1,c=0;
        StringBuilder r=new StringBuilder();
        while(i>=0||j>=0||c>0){
            int s=c;
            if(i>=0)s+=a.charAt(i--)-'0';
            if(j>=0)s+=b.charAt(j--)-'0';
            r.append(s%2);
            c=s/2;
        }return r.reverse().toString();
    }
}