Kai*_*Bum 1 java methods recursion
所以我试图学习递归(我知道在这种情况下递归是没有必要的)
我已经写过这个方法,它有效
public static int method(int number) {
if(number == 0) {
return 1;
}
else {
return (int)Math.pow(2,number) + method(number-1);
}
}
Run Code Online (Sandbox Code Playgroud)
这适用于将2的幂从0加到数字,但我想知道是否有一种方法来替换Math.pow()另一个递归方法调用
您可以将其用作递归幂函数:
public static int powerOf2(int number) {
if (number == 0) {
return 1;
} else {
return 2 * powerOf2(number - 1);
}
}
Run Code Online (Sandbox Code Playgroud)
或者,作为一个单体:
return number > 0 ? 2 * powerOf2(number - 1) : 1;
Run Code Online (Sandbox Code Playgroud)