Java Program to Convert a Binary Number to a Decimal Number Using Recursion

You are currently viewing Java Program to Convert a Binary Number to a Decimal Number Using Recursion

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

// Java program to convert a binary number to a decimal number
// using the recursion

import java.util.*;

public class Main {
  public static int binToDec(String bin, int index) {
    int len = bin.length();

    if (index == len - 1)
      return bin.charAt(index) - '0';

    return ((bin.charAt(index) - '0') << (len - index - 1)) + binToDec(bin, index + 1);
  }

  public static void main(String[] args) {
    Scanner X = new Scanner(System.in);

    String bin;
    int res;

    System.out.printf("Enter binary number: ");
    bin = X.next();

    res = binToDec(bin, 0);
    System.out.printf("Decimal number is: " + res);
  }
}

Output

Enter binary number: 10111001
Decimal number is: 185

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply