Write a Java program to convert a binary number to a decimal number using recursion


This program converts a binary number to a decimal number. It takes user input for a binary number as a string and uses recursion to convert it to a decimal number.

The binaryToDecimal method takes two arguments: the binary number string and the index of the current digit being converted. It recursively calculates the decimal value of the binary number by starting at the leftmost digit (index 0) and moving towards the right.

On each recursive call, it shifts the decimal value of the current digit to its appropriate place value and adds it to the sum of the remaining digits. The shift amount is determined by subtracting the current index from the length of the binary string minus one.

The base case of the recursion is when the index reaches the last digit of the binary string. At this point, it returns the decimal value of the final digit.

Finally, the main method takes user input for a binary number and passes it to the binaryToDecimal method to get the decimal equivalent, which it then prints to the console.

Source Code

import java.util.*;
public class BinToDec
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.printf("Enter the Binary Number : ");
		String bin = input.next();
 
		int dec = binaryToDecimal(bin, 0);
		System.out.printf("Decimal Number : " + dec);
	}
	public static int binaryToDecimal(String bin, int ind)
	{
		int len = bin.length();
		if (ind == len - 1)
		{
			return bin.charAt(ind) - '0';
		}
		return ((bin.charAt(ind) - '0') << (len - ind - 1)) + binaryToDecimal(bin, ind + 1);
	}
}

Output

Enter the Binary Number : 101010
Decimal Number : 42