我需要在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;
}
Run Code Online (Sandbox Code Playgroud)
上面的方法是否准确,因为在调试后我发现当结果超过Integer.MAX_VALUE时它会转到负数,还是有另一种方法来处理这个?
小智 4
如果基数只能是正整数,您的方法将起作用。如果基数是负整数,而幂是奇数,则可能会发生下溢。
处理这种情况的一个简单但不是最佳的方法是使用 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1358 次 |
| 最近记录: |