Complete the Recursive base conversion practice problem before reviewing the solution.

Review the Recursive base conversion practice problem with AP CS Tutor Brandon Horn.

Part (a) toBinary method

public static void toBinary(int inBase10)
{
    if(inBase10 <= 1)
    {
        System.out.print(inBase10);
        return;
    }

    toBinary(inBase10 / 2);
    System.out.print(inBase10 % 2);
}

Part (b) toDecimal method

public static int toDecimal(String inBase2)
{
    if(inBase2.length() == 0)
        return 0;

    int restAsInt = toDecimal(inBase2.substring(1));

    if(inBase2.substring(0, 1).equals("0"))
        return restAsInt;
    else
        return (int) (Math.pow(2, inBase2.length() - 1)) + restAsInt;
}

Comments

Comment on Recursive base conversion