The problem requires adding two binary strings and returning the result as a binary
string. To achieve this, we
reverse both input
strings to
simplify the
addition process starting from the
least significant bit. We
then
iterate through
the strings,
adding
corresponding bits along with any
carry from the previous
addition. The
sum of
the bits and the carry is used to
determine the current bit
of the result and the new carry. Finally, we reverse the result string to get the correct order.
class Solution { public String addBinary(String a, String b) { StringBuilder sb = new StringBuilder(); int i = a.length() - 1; int j = b.length() - 1; int carry = 0; while (i >= 0 || j >= 0 || carry != 0) { int digit1 = (i >= 0) ? a.charAt(i)-'0' : 0; int digit2 = (j >= 0) ? b.charAt(j)-'0' : 0; int sum = digit1 + digit2 + carry; sb.append(sum%2); carry = sum/2; i--; j--; } return sb.reverse().toString(); } }
The algorithm iterates through the longer of the two input strings once, making it linear in time complexity.
The algorithm uses additional space to store the result string, which is proportional to the input size.