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
1010 + 1011 = 10101
Zero sum
1 + 0 = 1
11 + 1 = 100
111 + 111 = 1110
Algorithm Flow
Solution Approach
Add binary digits from right to left, tracking the carry and building the 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
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.
