Now you are ready to perform the recursion trick: You replace the call to
powerOf2
in recursivePowerOf2
by a call to
recursivePowerOf2
itself:
public static int recursivePowerOf2 (int n) {
if (n == 0) {return 1;}
else {
return 2 * recursivePowerOf2(n - 1);
}
}
The new version works for two reasons:
n
, is 0
,
recursivePowerOf2
returns 1
.
n
is not 0
, recursivePowerOf2
asks itself to compute the power of 2 for a number that is 1 less than
the value of n
. Then, recursivePowerOf2
may ask itself
to compute the power of 2 for a number that is 2 less than the original
value of n
, and so on, until the recursivePowerOf2
needs to deal with only 0
.