采用递归的方法,将Pow(x,n),转化为Pow(x,n/2)*Pow(x,n/2)。
将时间从O(n)变成O(logn)关键是写出边界条件。并注意定义double类型的tmp=pow(x,n/2).对n的正负以及奇偶做判断。
class Solution {
public double myPow(double x, int n) {
if (n==0) return 1;
if (n==1) return x;
if (n==-1) return 1/x;
double tmp=myPow(x,n/2);
tmp *= tmp;
if (n%2==0){
}else{
if (n<0) tmp *= 1/x;
else tmp*=x;
}
return tmp;
}
}