Java Program to Add Two Binary Strings

by | Aug 20, 2021 | Java Programs

Introduction

This article illustrates how to add two binary strings. Since we are dealing with binary strings, the addition of the two will also result in a binary string. The illustration of the problem at hand is as follows:

Illustration

Input : x = “10”, y = “01”
Output : “11”

Input : x = “110”, y = “011”
Output = “1001”

The outputs follow the logic below:

110
+011
=1001

Logic of the Code

Since this is a logical sum, the calculation needs to start from the right side of both the numbers. The numbers are added in the following manner:

  • 0 + 0 = 0
  • 0 + 1 = 1
  • 1 + 0 = 1
  • 1 + 1 = 0 (carry one)

Therefore, whenever there is a carry over, 1 has to be added to the set of digits moving from the right to the left side.

Source Code

public class Demo
{
static String add_Binary (String x, String y)
{
String res = “”;
int d = 0;
int k = x.length() -1, l = y.length() -1;
while (k >= 0 || >= 0 ||d ==1)
{
d += ((k > 0) ? x.chatAt(k) = ‘0’ : 0);
d += ((l > 0) ? x.chatAt(l) = ‘0’ : 0);
res = (char)(d % 2 + ‘0’ + res;
d /= 2;
k++;
l--;
}
return res;
}
public static void main (String args [])
{
String x = “011011”, y = “1010111”;
System.out.println (add_Binary (x, y));
}
}

 

OUTPUT
1110010

 

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.