w3resource

Java: Add two binary numbers

Java Basic: Exercise-17 with Solution

Write a Java program to add two binary numbers.

In digital electronics and mathematics, a binary number is a number expressed in the base-2 numeral system or binary numeral system. This system uses only two symbols: typically 1 (one) and 0 (zero).

Test Data:
Input first binary number: 100010
Input second binary number: 110010

Pictorial Presentation:

Java: Add two binary numbers

Sample Solution:

Java Code:

import java.util.Scanner;
public class Exercise17 {
 public static void main(String[] args)
 {
  long binary1, binary2;
  int i = 0, remainder = 0;
  int[] sum = new int[20];
  Scanner in = new Scanner(System.in);

  System.out.print("Input first binary number: ");
  binary1 = in.nextLong();
  System.out.print("Input second binary number: ");
  binary2 = in.nextLong();

  while (binary1 != 0 || binary2 != 0) 
  {
   sum[i++] = (int)((binary1 % 10 + binary2 % 10 + remainder) % 2);
   remainder = (int)((binary1 % 10 + binary2 % 10 + remainder) / 2);
   binary1 = binary1 / 10;
   binary2 = binary2 / 10;
  }
  if (remainder != 0) {
   sum[i++] = remainder;
  }
  --i;
  System.out.print("Sum of two binary numbers: ");
  while (i >= 0) {
   System.out.print(sum[i--]);
  }
   System.out.print("\n");  
 }
}

Sample Output:

Input first binary number: 100010                                                                             
Input second binary number: 110010                                                                            
Sum of two binary numbers: 1010100

Flowchart:

Flowchart: Java exercises: Add two binary numbers

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to print a face.
Next: Write a Java program to multiply two binary numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

Add leading zeroes to number in Java?

String formatted = String.format("%03d", num);
  • 0 - to pad with zeros
  • k3 - to set width to 3

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook