so im trying to learn recursion (i know in this case recursion is not necessary)
i have already written this method, which works
public static int method(int number) {
if(number == 0) {
return 1;
}
else {
return (int)Math.pow(2,number) + method(number-1);
}
}
this works perfectly for summing the powers of 2 from 0 to number, but i was wondering if there was a way to replace the Math.pow() with another recursive method call
解决方案
You can use this as a recursive power function:
public static int powerOf2(int number) {
if (number == 0) {
return 1;
} else {
return 2 * powerOf2(number - 1);
}
}
Or, as a one-line body:
return number > 0 ? 2 * powerOf2(number - 1) : 1;