gpt4 book ai didi

java - 我需要编写只返回整数幂的方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:48:44 24 4
gpt4 key购买 nike

我需要在 java 中编写一个方法来仅返回整数的幂,并且我希望此方法返回 -1 或在数字超过 Integer.MAX_VALUE 时引发异常:

我尝试了第一个简单的步骤:

public static int GetPower(int base, int power)
{
int result = 1;

for(int i = 1; i<=power; i++)
{
result *= base;
if (result < 0 ) {
break; // not very acurate
}
}
if (result < 0 ) {
return -1;
}
return result;
}

上面的方法是否准确,调试后发现当结果超过Integer.MAX_VALUE时会变成负数,还是有其他方法处理?

最佳答案

如果基数只能是正整数,您的方法将起作用。底数为负整数,幂为奇数,可能会发生下溢。

处理这种情况的一种简单但不是最佳的方法是使用 long 数据类型来存储输出并比较输出以检查它是否在 Integer.MAX_VALUE 和 Integer.MIN_VALUE 之间。

public static int GetPower(int base, int power){
long result = 1;

for(int i = 1; i <= power; i++)
{
result *= base;
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
return -1;
}
}
return result;
}

关于java - 我需要编写只返回整数幂的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30940422/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com