For the LeetCode algorithm problem #50 Pow(x, n). Why I got an stack overflow error if I put checking n is positive or negative within the recursive function? But if I put the checking outside the recursive function then it will accept. The test case is 1.000 -2147483648
Checking within the recursive function.
class Solution {
public double myPow(double x, int n) {
if (n < 0) {
x = 1 / x;
n = -n;
return myPow(x,n);
}
if (n == 0) {
return 1.0;
}
double half = myPow(x, n / 2);
if (n % 2 == 0) {
return half * half;
} else {
return half * half * x;
}
}
}
Checking outside the recursive function.
class Solution {
private double fastPow(double x, long n) {
if (n == 0) {
return 1.0;
}
double half = fastPow(x, n / 2);
if (n % 2 == 0) {
return half * half;
} else {
return half * half * x;
}
}
public double myPow(double x, int n) {
long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
return fastPow(x, N);
}
}
myPowis exposed as a public method so cannot be tail-optimized. The code works fine, but the possible range ofnis limited by stack space. See this post for an example.