Write a recursive binary to decimal function in java that ta
Write a recursive binary to decimal function in java that takes a string representation of a binary number and and converts it to a decimal value which is returned from the function. For instance, given the string \"1111\", the function should return 15.
Solution
Please follow the code and comments for description :
CODE :
import java.util.Scanner; // required imports
public class BinToDec { // class to run the code
public static void main(String[] args) { // driver method
String n; // local variables
int x;
Scanner s = new Scanner(System.in); // scanner class to read the data
System.out.print(\"Enter the Binary number : \"); // prompt for the user
n = s.nextLine(); // get the data
x = BinToDec.binaryToDecimalConv(n); // call the method to return the data
System.out.println(\"The Converted Decimal Number is : \" + x); // print the data to console
}
public static int binaryToDecimalConv(String binInput) { // method that takes the binary and return the decimal values
int len = binInput.length(); // get the length
if (len == 0) { // check for the length
return 0;
}
String now = binInput.substring(0, 1); // get the values one by one
String later = binInput.substring(1);
return Integer.parseInt(now) * (int) Math.pow(2, len - 1) + binaryToDecimalConv(later); // recursively call the method
}
}
OUTPUT :
Enter the Binary number : 1111
The Converted Decimal Number is : 15
Hope this is helpful.
