英文:
Math Power(x,n) does not work -2147483648 for in java?
问题
I am doing a leetcode problem.
https://leetcode.com/problems/powx-n/
> 实现 pow(x, n),计算 x 的 n 次方(即 x^n)。
I have no idea why last test case is failing, x^-2147483648 returns 1 instead of 0.
- 为什么这应该首先返回 0?
- 此外,调试器中的 Math.abs(n) 仍然返回负数 -2147483648。
--
Code:
class Solution {
public double myPow(double x, int n) {
if (n == 0)
return 1;
if (n < 0) {
return 1 / getDFS(x, Math.abs(n));
}
return getDFS(x, n);
}
private double getDFS(double x, int n) {
if (n == 1) {
return x;
}
double saveData = 1;
if (n / 2 >= 1) {
int newN = n / 2;
saveData = getDFS(x,newN);
}
if (n % 2 == 1) {
return saveData * saveData * x;
}
return saveData * saveData;
}
}
Results:
英文:
I am doing a leetcode problem.
https://leetcode.com/problems/powx-n/
> Implement pow(x, n), which calculates x raised to the power n (i.e.,
> x^n).
I have no idea why last test case is failing, x^-2147483648 returns 1 instead of 0.
- Why should this even return 0 in first place?
- Also, Math.abs(n) in debugger still returns a negative -2147483648.
--
Code:
class Solution {
public double myPow(double x, int n) {
if (n == 0)
return 1;
if (n < 0) {
return 1 / getDFS(x, Math.abs(n));
}
return getDFS(x, n);
}
private double getDFS(double x, int n) {
if (n == 1) {
return x;
}
double saveData = 1;
if (n / 2 >= 1) {
int newN = n / 2;
saveData = getDFS(x,newN);
}
if (n % 2 == 1) {
return saveData * saveData * x;
}
return saveData * saveData;
}
}
Results:
答案1
得分: 1
最小负整数的绝对值比最大正整数的绝对值要大。因此 `Math.abs` 无法返回 `Integer.MIN_VALUE` 的正确值。
为了解决这个问题,在使用二进制指数之前,你可以将指数转换为 `long` 类型。
```java
public double myPow(double x, int n) {
if (n == 0)
return 1;
if (n < 0) return 1 / getDFS(x, Math.abs((long) n));
return getDFS(x, n);
}
private double getDFS(double x, long n) {
// ...
if (n / 2 >= 1) {
long newN = n / 2;
saveData = getDFS(x,newN);
}
// ...
}
英文:
The magnitude of the smallest negative int
value is larger than the magnitude of the largest positive int
value. Thus Math.abs
cannot return the correct value for Integer.MIN_VALUE
.
To solve this problem, you can cast the exponent to long
before using binary exponentiation.
public double myPow(double x, int n) {
if (n == 0)
return 1;
if (n < 0) return 1 / getDFS(x, Math.abs((long) n));
return getDFS(x, n);
}
private double getDFS(double x, long n) {
// ...
if (n / 2 >= 1) {
long newN = n / 2;
saveData = getDFS(x,newN);
}
// ...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论