The problem is classic example of recursion. Here it is important to understand the range of n. For this case we will consider n can be positive or negative
Example pow(2,3) = 8
pow(4,2) = 16
pow(2,-1) = 0.5
public double myPow(double x, int n) {
if (n == 0)
return 1;
double temp = myPow(x, n / 2);
if (n % 2 == 0)
return temp * temp;
else if (n > 0) {
return x * temp * temp;
} else {
return (temp * temp) / x;
}
}