Recursive:
public class Solution {
public double pow(double x, int n) {
if ( n == 0 )
return 1;
double half = pow ( x, n/2);
double res = 1.0;
if ( n % 2 == 0 ){
res = half * half;
}
else if ( n > 0)
res = half * half * x;
else
res = half * half / x;
return res;
}
}
Iterative:
public class Solution {
public double pow(double x, int n) {
if ( n == 0 )
return 1;
double res = 1.0;
for ( int i = n; i != 0; i/=2 ){
if ( i % 2 != 0 )
res *= x;
x *= x;
}
if ( n < 0 )
res = 1.0/res;
return res;
}
}