Solution to Recursive base conversion practice problem

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)

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

Part (b)

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

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

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

Get AP CS Help

Leave a Reply