Skip to content
Related Articles

Related Articles

Improve Article

Java Program to Add Two Binary Strings

  • Difficulty Level : Easy
  • Last Updated : 28 Mar, 2021
Geek Week

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

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’s see a program in order to get the clear concept of 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)
    {
  
        // Initializing result
        String res = "";
  
        // Initializing digit sum
        int d = 0;
  
        // Traversing both the strings starting
        // from the last characters
        int k = x.length() - 1, l = y.length() - 1;
        while (k >= 0 || l >= 0 || d == 1) {
  
            // Computing the sum of last
            // digits and the carry
            d += ((k >= 0) ? x.charAt(k) - '0' : 0);
            d += ((l >= 0) ? y.charAt(l) - '0' : 0);
  
            // When the current digit's sum is either
            // 1 or 3 then add 1 to the result
            res = (char)(d % 2 + '0') + res;
  
            // Computing carry
            d /= 2;
  
            // Moving to the next digits
            k--;
            l--;
        }
  
        return res;
    }
  
    // The Driver code
    public static void main(String args[])
    {
        String x = "011011", y = "1010111";
  
        System.out.print(add_Binary(x, y));
    }
}
Output
1110010

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :