question archive Write a method that parses a binary number as a string into a decimal integer
Subject:Computer SciencePrice:2.89 Bought3
Write a method that parses a binary number as a string into a decimal integer. The method header is as follows:
public static int binary to Decimal(String binaryString)
For example, binary string 10001 is 17 (1 x 24 + 0 x 23 + 0 x 22 + 0 x 2 + 1 = 17)
So, binary to Decimal ("10001") returns 17. Note that Integer.parseInt("10001", 2) parses a binary string to a decimal value.
Do not use this method in this exercise.
Write a test program that prompts the user to enter a binary string and displays the corresponding decimal integer value.
import java.util.*;
public class tester
{
public static int binaryToDecimal(String binaryString)
{
if(binaryString.length() == 1) return (int)(binaryString.charAt(0)-'0');
else
return 2*binaryToDecimal(binaryString.substring(0,binaryString.length()-1))+(binaryString.charAt(binaryString.length()-1)-'0');
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a binay number in string format :");
String str = in.next();
System.out.println("Decimal Number is " + binaryToDecimal(str));
}