Java: Add two binary numbers
Binary Addition
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:
Sample Solution:
Java Code:
Explanation:
In the exercise above -
- Initialize variables to store the two binary numbers ('binary1' and 'binary2'), an array 'sum' to store the sum, and other necessary variables.
- Takes two binary numbers from the user using the "Scanner" class.
- Next it enters a loop to perform binary addition from the least significant digit (rightmost) to the most significant digit (leftmost).
- Calculate the sum of the corresponding digits from both binary numbers and any remainder from the previous addition.
- Store the least significant digit of the sum in the 'sum' array.
- Update the remainder and divide both input binary numbers by 10 to move to the next digit.
- After the loop, if there's still a remainder left, it adds it to the 'sum' array.
- Prints the sum of the two binary numbers by iterating through the 'sum' array from the most significant digit to the least significant digit.
- The result is displayed as a binary number.
Sample Output:
Input first binary number: 100010 Input second binary number: 110010 Sum of two binary numbers: 1010100
Flowchart:
For more Practice: Solve these Related Problems:
- Write a program to add three binary numbers instead of two.
- Perform binary addition without converting to decimal.
- Write a program that adds two binary numbers of different lengths.
- Modify the program to add hexadecimal numbers instead of binary.
Java Code Editor:
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.