Java Program to add Two Binary Strings
In this article, we are going to understand how to add two binary strings, basically binary strings a sequence of numbers represented by 0s and 1s. Binary string addition refers to the process of adding two binary numbers represented as strings. the addition of binary strings follows similar rules to decimal addition but with a base of 2 instead of 10.
Example 1
Input:
String1: 1011
String2: 0101
Output:
Addition: 10000
Explanation: According to the binary addition rule we have to start from the leftmost digits. So the first two elements are 1 and 1 so the addition is 0 and carry 1. Then the next two digits are 1 and 0 but we also have to carry 1 to add in this so it will return 0 and carry 1. Now the next digits are 0 and 1 then add carry 1 in this also now it will return 0 and carry 1 also. Now last two digits are 1 and 0 but so add carry 1 in it now it returns 0 and carry 1. In the end, we get an output of 10000.
Approach: Using the StringBuilder class
StringBuilder is a class in Java that provides a mutable sequence of characters. It is part of the java.lang package and is commonly used when you need to manipulate strings efficiently. Finally, we convert the StringBuilder to a String using the toString method and print the result.
FileName:BinaryAddition.java
public class BinaryAddition { public static String addBinaryStrings(String str1, String str2) { StringBuilder result = new StringBuilder(); // To store the result int carry = 0; // To store the carry value int i = str1.length() - 1; // Starting index for str1 int j = str2.length() - 1; // Starting index for str2 // Iterate through the binary strings from right to left while (i >= 0 || j >= 0) { int sum = carry; // Initialize sum with the carry value // Add the corresponding bits from str1 and str2 if (i >= 0) sum += str1.charAt(i--) - '0'; // Convert char to int if (j >= 0) sum += str2.charAt(j--) - '0'; // Convert char to int result.insert(0, sum % 2); // Insert the sum modulo 2 at the beginning of the result carry = sum / 2; // Update the carry value } // If there is a remaining carry, insert it at the beginning of the result if (carry != 0) result.insert(0, carry); return result.toString(); // Convert the StringBuilder to a string and return it as the final result } public static void main(String[] args) { String str1 = "1011"; String str2 = "0101"; String sum = addBinaryStrings(str1, str2); System.out.println("The addition of Binary String is: " + sum); } }
Output:
The addition of Binary String is: 10000
Approach: Using an Array
In this approach, we create an integer array result to store the digits of the resulting binary string. We iterate from the highest significant bit to the lowest, performing the addition of corresponding bits from the input strings along with the carry. We store the calculated digit in the result array and update the carry. After the loop, we construct the final binary string by appending the digits from the result array to a StringBuilder, taking care to append the final carry if it exists.
FileName: BinaryAddition.java
public class BinaryAddition { public static String addBinaryStrings(String str1, String str2) { int maxLength = Math.max(str1.length(), str2.length()); int[] result = new int[maxLength + 1]; // +1 to accommodate carry int carry = 0; int index1 = str1.length() - 1; int index2 = str2.length() - 1; int resultIndex = maxLength; // Starting index for result while (index1 >= 0 || index2 >= 0 || carry != 0) { // Get the current binary digits, converting characters to integers int digit1 = (index1 >= 0) ? str1.charAt(index1--) - '0' : 0; int digit2 = (index2 >= 0) ? str2.charAt(index2--) - '0' : 0; // Calculate the sum of digits and carry int sum = digit1 + digit2 + carry; result[resultIndex] = sum % 2; // Store the current digit carry = sum / 2; // Calculate the carry resultIndex--; } StringBuilder sb = new StringBuilder(); // Construct the final binary string by appending the calculated digits for (int i = 0; i <= maxLength; i++) { sb.append(result[i]); } return sb.toString(); } public static void main(String[] args) { String str1 = "1011"; String str2 = "0101"; String sum = addBinaryStrings(str1, str2); System.out.println("The addition of Binary String is: " + sum); } }
Output:
The addition of Binary String is: 10000
Approach: Using a Binary-to-Integer Conversion
In this approach, we use a Binary-to-Integer Conversion to convert the binary strings str1 and str2 to integers using the parseInt method with a radix of 2, indicating the base is binary. The integers num1 and num2 are then added using the + operator, performing integer addition.
FileName: BinaryAddition.java
public class BinaryAddition { public static String addBinaryStrings(String str1, String str2) { int maxLength = Math.max(str1.length(), str2.length()); int[] result = new int[maxLength + 1]; // +1 to accommodate carry int carry = 0; int index1 = str1.length() - 1; int index2 = str2.length() - 1; int resultIndex = maxLength; // Starting index for result while (index1 >= 0 || index2 >= 0 || carry != 0) { // Get the current binary digits, converting characters to integers int digit1 = (index1 >= 0) ? str1.charAt(index1--) - '0' : 0; int digit2 = (index2 >= 0) ? str2.charAt(index2--) - '0' : 0; // Calculate the sum of digits and carry int sum = digit1 + digit2 + carry; result[resultIndex] = sum % 2; // Store the current digit carry = sum / 2; // Calculate the carry resultIndex--; } StringBuilder sb = new StringBuilder(); // Construct the final binary string by appending the calculated digits for (int i = 0; i <= maxLength; i++) { sb.append(result[i]); } return sb.toString(); } public static void main(String[] args) { String str1 = "1011"; String str2 = "0101"; String sum = addBinaryStrings(str1, str2); System.out.println("The addition of Binary Strings is: " + sum); } }
Output:
The addition of Binary Strings is: 10000