LeetCode Pow(x, n)
Implement pow(x, n).
思路分析:经典面试题,考察分治和递归,之前在百度面试碰见过。
AC Code
public class Solution {
public double pow(double x, int n) {
if(n < 0) return 1.0 / power(x, -n);
else return power(x, n);
}
public double power(double x, int n){
//For positive n
if(n == 0) return 1;
double v = power(x, n/2);
if(n % 2 == 1){
return v * v * x;
} else{
return v * v;
}
}
}