When two binary strings are added, the result is also a binary string. Java provides multiple ways to perform binary addition, depending on constraints such as input size and performance requirements.
Example:
Input : x = "110", y = "011"
Output: "1001"
Explanation:
110
+ 011
=1001
Approach 1: Using Built-in Conversion
In this approach, binary strings are converted to decimal integers, added, and then converted back to a binary string.
Algorithm
- Convert both binary strings to decimal using Integer.parseInt(str, 2).
- Add the decimal values.
- Convert the sum back to binary using Integer.toBinaryString().
class GFG {
static String addBinary(String x, String y) {
int num1 = Integer.parseInt(x, 2);
int num2 = Integer.parseInt(y, 2);
int sum = num1 + num2;
return Integer.toBinaryString(sum);
}
public static void main(String[] args) {
String x = "011011";
String y = "1010111";
System.out.println(addBinary(x, y));
}
}
Output
1110010
Limitations:
- Works only when values fit within integer range
- Not suitable for very large binary strings
Approach 2: Two-Pointer (Manual Binary Addition)
This approach simulates binary addition bit by bit without converting to decimal, making it suitable for large inputs.
Algorithm
- Initialize two pointers at the end of both strings.
- Maintain a carry variable.
- Add corresponding bits and carry.
- Append the result bit to a StringBuilder.
- Reverse the result at the end.
class GFG {
public static String addBinary(String x, String y) {
int i = x.length() - 1;
int j = y.length() - 1;
int carry = 0;
StringBuilder result = new StringBuilder();
while (i >= 0 || j >= 0) {
int sum = carry;
if (i >= 0) sum += x.charAt(i--) - '0';
if (j >= 0) sum += y.charAt(j--) - '0';
result.append(sum % 2);
carry = sum / 2;
}
if (carry == 1) {
result.append(1);
}
return result.reverse().toString();
}
public static void main(String[] args) {
String x = "011011";
String y = "1010111";
System.out.println(addBinary(x, y));
}
}
Try it on GfG Practice
Output
1110010
Key Points:
- Built-in methods are simpler but limited by integer range.
- Two-pointer approach is preferred for large binary strings.
- Manual addition avoids overflow and improves reliability.
- StringBuilder improves performance over string concatenation.