Problem: Write a Java Program to convert a decimal number into its binary representation.

Example:

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.

Method 1: Using While Loop

decimal to binary

To convert decimal into binary, we divide the decimal number by 2 until it reduces to 0.

The bottom-up sequence of the remainders that we get after division is the binary representation of the corresponding decimal number.

In Java, we use implement the same using a while loop as follows:

Output:

Enter a number
5
Binary: 101

Method 2: Using Recursion

The logic to convert a decimal into binary is same as the above method, but is implemented using recursion.

Output:

Enter a number
15
Binary: 1111

In this method, we pass the quotient of the current division to the next recursive call. We do this until the passed number is reduced to zero.

The important part of the recursive function is the print statement. In the print statement, we are printing the remainder of the current division, which is written after the recursive call.

Because of this, the remainders start printing from the last recursive call, so gets printed in a bottom-up manner (resulting binary).

Leave a Reply

12 − 9 =