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: