Given two binary strings a
and b
, return their sum as a binary string.
You may assume that the input strings are non-empty and only contain characters 1
and 0
.
0
.StringBuilder
to store the result.StringBuilder
.StringBuilder
.StringBuilder
to get the final binary sum string.Here’s the Java implementation of the above strategy:
public class AddBinary {
public String addBinary(String a, String b) {
StringBuilder result = new StringBuilder();
int carry = 0;
int i = a.length() - 1; // Pointer for string a
int j = b.length() - 1; // Pointer for string b
while (i >= 0 || j >= 0) {
int sum = carry;
if (i >= 0) {
sum += a.charAt(i) - '0'; // Convert character to integer
i--;
}
if (j >= 0) {
sum += b.charAt(j) - '0'; // Convert character to integer
j--;
}
result.append(sum % 2); // Append the binary digit
carry = sum / 2; // Calculate the new carry
}
if (carry != 0) {
result.append(carry); // If there is any carry left, append it
}
return result.reverse().toString(); // Reverse the result to get the correct binary sum
}
}
N
and M
are the lengths of the input strings a
and b
, respectively. This is because we traverse both strings once.This solution efficiently handles the addition of two binary strings and ensures correctness with the appropriate handling of carry-over.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?