# Recursive base conversion practice problem2

Conversion between bases is typically a single question on the AP Computer Science Exam. In this practice problem, you’ll be presented with algorithms to convert between base 10 and another base then asked to implement each algorithm as a recursive method. Base 2 is used as the non-integer base in throughout this problem; however, both algorithms work with any base.

The AP CS Pictures Lab features numbers in different bases.

On the Exam, if you are asked to perform arithmetic with numbers in a different base, convert them to base 10, perform the arithmetic, then convert the result into the required base if necessary. Do not attempt to perform arithmetic with numbers in

## Part (a)

Consider the following 2 examples of a simple algorithm to convert an integer (base 10) to a binary number (base 2).

```(12)10 = (?)2
12 /2 = 6 R0
6 / 2 = 3 R0
3 / 2 = 1 R1
1 / 2 = 0 R1
(12)10 = (1100)2
```
```(34)10 = (?)2
34 / 2 = 17 R0
17 / 2 = 8  R1
8 / 2  = 4  R0
4 / 2  = 2  R0
2 / 2  = 1  R0
1 / 2  = 0  R1
(34)10 = (100010)2
```

The method toBinary recursively prints the binary (base 2) representation of inBase10. For example, toBinary(12) prints 1100. toBinary(34) prints 100010.

The method’s precondition is: inBase10 > 0.

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

/* to be completed in part (a) */
}
```

Give code to replace /* to be completed in part (a) */.

## Part (b)

Consider the following two examples of converting a binary number (base 2) to an integer (base 10).

```(11010)2 = (?)10
1    1    0    1    0
24   23   22   21   20
16 + 8 +  0 +  2 + 0 = 26
(11010)2 = (26)10
```
```(100010)2 = (?)10
1    0    0    0    1   0
25   24   23    22   21  20
32 + 0 +  0  + 0 +  2 + 0 = 34
(100010)2 = (34)10
```

The method toInteger recursively converts inBase10 to an integer (base 10) and returns the integer representation. For example, toInteger("11010") returns 26. toInteger("100010") returns 34.

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

/* to be completed in part (b) */
}
```

Give code to replace /* to be completed in part (b) */.

See the Recursive base conversion practice problem solution or review it with AP CS Tutor Brandon Horn. ## 2 thoughts on “Recursive base conversion practice problem”

Looking at your code below, for int inBase2 declaration, there is no such thing as inBase2.length().

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

/* to be completed in part (b) */
}

• Brandon Horn

Sorry about that. `inBase2` was supposed to be a `String`, not an `int`.