因此,我正在制作的递归函数需要 2 个变量( x
和 y
)并计算 x
的幂y
。就像 Math.pow
功能。 y
是正数,所以我不需要担心负指数。
这是我的代码:
public static int power(int x, int y) {
if (y == 0)
return 1;
else
return x * power(x, y-1);
}
起初看起来效果很好,但后来我尝试输入 power(50,6)
。我得到了-1554869184
。
显然这是错误的,因为正确答案不能是否定的。
最佳答案
你的方法很好,但是对于太长的数字不起作用。
int
有 4 个字节(32 位)=> 最大值为 2147483647
( 2^31-1
),总计: 2^32
值(也有一些负数)
long
有 8 个字节(64 位)=> 最大值为 9223372036854775807
( 2^63-1
),总计: 2^64
值
这些值可以在 Java 中使用以下方法找到:
Integer.MAX_VALUE // Integer and int have the same range
Long.MAX_VALUE // Long and long have also the same range
对于您的情况:
50^6 = 15625000000
是有效的 long
数字,但不是有效的 int
(它大于 2^32-1
)
小心:
如果您尝试使用更长的数字,您也可能会遇到 long
问题。
例如:
power(10,18); // OK
power(10,19); // not OK: negative number
power(10,20); // not OK: even if the number is positive
// the answer is not good - it has only 18 digits!
关于java - 简单的 Java 幂递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25835595/