Optimal: halve the exponent
Time O(log n) Space O(log n) stackCompute half = pow(x, n / 2) once, square it, and multiply by x if n is odd. Use a long for n so −Integer.MIN_VALUE doesn't overflow.
class Solution {
public double myPow(double x, int n) {
long N = n; // -Integer.MIN_VALUE overflows an int
if (N < 0) { x = 1 / x; N = -N; }
return pow(x, N);
}
private double pow(double x, long n) {
if (n == 0) return 1.0;
double half = pow(x, n / 2);
return (n % 2 == 0) ? half * half : half * half * x;
}
}Verdict: About 31 levels for any int exponent.