Showing posts with label Add two Binary Numbers in Java.. Show all posts
Showing posts with label Add two Binary Numbers in Java.. Show all posts

Tuesday, August 11, 2020

Write a Program to Add two Binary Numbers in Java.

Add two Binary Numbers in Java.

Add two Binary Numbers in Java.

Binary number system has only two symbols 0 & 1 so a binary numbers consists of only 0’s and 1’s. 
user enters the two binary numbers that we need to add

EXAMPLE :-

import java.util.Scanner;
public class binary {
public static void main(String[] args)
{
   long bin1, bin2;
   int i = 0, carry = 0;

   int[] sum = new int[10];
   Scanner scanner = new Scanner(System.in);
   System.out.print("Enter First Binary Number :: ");
   bin1 = scanner.nextLong();
   System.out.print("Enter Second Binary Number :: ");
   bin2 = scanner.nextLong();
   scanner.close();
   while (bin1 != 0 || bin2 != 0)
   {
      sum[i++] = (int)((bin1 % 10 + bin2 % 10 + carry) % 2);
      carry = (int)((bin1 % 10 + bin2 % 10 + carry) / 2);
      bin1 = bin1 / 10;
      bin2 = bin2 / 10;
   }
   if (carry != 0) {
      sum[i++] = carry;
   }
   --i;
   System.out.print("This is Output :: ");
   while (i >= 0) {
      System.out.print(sum[i--]);
   }
   System.out.print("\n");
}
}

OUTPUT


Enter First Binary Number :: 100011 Enter Second Binary Number :: 110001 This is Output :: 1010100