Write a Java Program to Convert a decimal number into its binary representation.

Example:

The method is very simple. We need to divide the decimal number by 2 until it reduces to 0. The remainders which we will get in reverse order will give the binary representation of the corresponding decimal number.

decimal to binary

To achieve the remainder in the bottom-up manner we need to concatenate each of the upcoming remainders to the left of the concatenated binary number. For this, we will need to first multiply equal number 10 to the remainder as the number of digits already present in the concatenated binary number and then add to the concatenated binary number.

Let’s implement the same in Java.

Convert Decimal to Binary in Java using While Loop

Output

Enter a number
5
Binary: 101

Convert Decimal to Binary in Java using Recursion

In this method we will pass the quotient to each recursive call until it reduces to zero, then will start outputting the remainder from the last.

Since recursion implements stack, so the output of the remainder will happen from the last recursive call.

Output

Enter a number
15
Binary: 1111

Comment below your suggestion or doubts if you have any.

Leave a Reply

Close Menu