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

Example:

Method 1: Using While Loop

Binary to Decimal

To convert a binary into a decimal we multiply the digits of the binary with their respective exponential value of 2 (2position from right – 1) and sum them up.

To iterate through the digits in Java, we use the while loop as follows:

Output:

Enter a Binary: 101
Decimal: 5

Method 2: Using Recursion

The approach used in this method is the same as the above but implemented in a recursive fashion.

On every recursive call, we extract the last digit, multiply it with its corresponding exponential value of 2 and return its sum with the next recursive call result.

Output:

Enter a Binary: 1111
Decimal: 15

It is important to note that on every next recursive call, we are eliminating the last digit from the binary number that has been processed in the current recursion.

If you have any doubts or suggestions then below.

Leave a Reply

15 − seven =