Code Logo

Add Binary Strings

Published at25 Jul 2026
Medium 0 views
Like0

Given two binary strings a and b, return their sum as a binary string. Binary strings contain only '0' and '1' characters. Do not convert to integers and back — implement the binary addition algorithm digit by digit.

Use two pointers starting from the rightmost digit. Track a carry. For each position, add the two digits plus the carry. The result digit is (sum % 2) and the new carry is Math.floor(sum / 2). Continue until both strings are exhausted and the carry is zero.

Time complexity is O(max(n,m)) and space is O(max(n,m)) for the result. This is a classic digit-by-digit addition problem that tests string manipulation and carry handling.

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
Recommendation Algorithm Flow for Add Binary Strings

Solution Approach

function solution(a, b) {
  var i = a.length - 1, j = b.length - 1, carry = 0, result = '';
  while (i >= 0 || j >= 0 || carry) {
    var sum = carry;
    if (i >= 0) sum += parseInt(a.charAt(i--));
    if (j >= 0) sum += parseInt(b.charAt(j--));
    result = (sum % 2) + result;
    carry = Math.floor(sum / 2);
  }
  return 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();
    }
}