Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String of binary digits to decimal number... using recursion

Comp sci professor gave us this problem in our homework... I'm not sure how to proceed and the code I have written seems to be failing miserably. Here is the prompt:


(binary to decimal) Write a recursive method that parses a binary number as a string into a decimal integer. The method header is:

public static String bin2Dec(String binaryString)

write a test program that prompts the user to enter a binary string and displays its decimal equivalent.


Any help greatly appreciated. Here is my code as follows:

import java.util.Scanner;

public class HW04_P5 {
    static int index = 0;
    static int power = 0;
    static int number = 0;
    static boolean exit = false;

    @SuppressWarnings("resource")
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        System.out.print("  Enter a binary number to convert to decimal: ");
        String in = scan.nextLine();
        index = in.length()-1;
        System.out.print("  Binary number converted to decimal:          "+bin2Dec(in));
    }

    public static String bin2Dec(String in)
    {
        if((in.substring(index,index+1).equals("1"))&&(index>0))
        {
            number += Math.pow(2,power);
            System.out.print(number);
            power++;
            index--;
            bin2Dec(in);
        }
        else if((in.substring(index,index+1).equals("0"))&&(index>0))
        {
            power++;
            index--;
            bin2Dec(in);
        }
        System.out.print(number);
        return "";
    }
}
like image 918
squeeler642 Avatar asked Jul 15 '26 17:07

squeeler642


1 Answers

It's cleaner not to have the extra variables index, power, and p. Just process the string from right to left. You also don't want the "global" variable number tracked outside the recursive function ... it's confusing and weird. You want all the state carried inside the recursive functions, in my opinion. Even with those restrictions, you can still do it in essentially two lines:

public static int bin2Dec(String s) {
  if (s == null || s.isEmpty()) return 0;
  else return s.charAt(s.length()-1)-48+2*bin2Dec(s.substring(0,s.length()-1));
}

That may not be the clearest solution, but it is the most elegant, I think. Clarity could be improved by breaking the else clause into several lines. 48 is the Unicode character number for 0, which is maybe not the best way to convert the characters '0' and '1' to their respective numbers.

like image 194
Edward Doolittle Avatar answered Jul 17 '26 16:07

Edward Doolittle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!