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
1010 + 1011 = 10101
Zero sum
1 + 0 = 1
11 + 1 = 100
111 + 111 = 1110
Algorithm Flow

Solution Approach
Best Answers
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();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
