A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/java-program-to-add-two-binary-strings/ below:

Java Program to Add Two Binary Strings

Java Program to Add Two Binary Strings

Last Updated : 19 May, 2023

Try it on GfG Practice

When two binary strings are added, then the sum returned is also a binary string.

Example:

Input :  x = "10", y = "01"
Output: "11"
Input :  x = "110", y = "011"
Output: "1001"
Explanation:
  110 
+ 011
=1001

Approach 1:

Here, we need to start adding from the right side and when the sum returned is more than one then store the carry for the next digits.

Let us see a program in order to get a clear concept of the above topic.

Example:

Java
// Java program to add two binary strings

public class GFG {

    // Function to add two binary strings
    static String add_Binary(String x, String y)
    {

        int num1 = Integer.parseInt(x, 2);
        // converting binary string into integer(decimal
        // number)

        int num2 = Integer.parseInt(y, 2);
        // converting binary string into integer(decimal
        // number)

        int sum = num1 + num2;
        // Adding those two decimal numbers and storing in
        // sum

        String result = Integer.toBinaryString(sum);
        // Converting that resultant decimal into binary
        // string

        return result;
    }

    // Main driver method
    public static void main(String args[])
    {
        String x = "011011", y = "1010111";

        System.out.print(add_Binary(x, y));
    }
}

Approach 2: Two Pointer

  1. Initialize two pointers at the end of both strings, let's call them i and j.
  2. Initialize a variable carry to 0.
  3. While i and j are greater than or equal to 0, do the following:
  4. If there is still a carry left over, add it to the front of the result string.
  5. Reverse the result string and return it.
Java
import java.io.*;

// Class
class GFG {

    // Method
    public static String addBinary(String x, String y)
    {
        int i = x.length() - 1, 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';
            }
            if (sum == 0 || sum == 1) {
                result.append(sum);
                carry = 0;
            }
            else if (sum == 2) {
                result.append("0");
                carry = 1;
            }
            else {
                result.append("1");
                carry = 1;
            }
            i--;
            j--;
        }
        if (carry == 1) {
            result.append("1");
        }
        return result.reverse().toString();
    }

    // Main driver method
    public static void main(String[] args)
    {
        String x = "011011";
        String y = "1010111";
      
        System.out.println(addBinary(x, y));
    }
}

Time complexity: O(max(N, M))
Auxiliary space: O(max(N, M))



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4