Implement pow(x, n).
看到这个题目,一开始以为是大数乘法,后来发现用递归也能做,使用递归将时间复杂度降为o(logn)。
class Solution {
public:
double pow(double x, int n) {
if(n==0) return 1;
if(n==1) return x;
double temp=pow(x,abs(n/2));
if(n>0){
if(n%2==0) return temp*temp;
else return temp*temp*x;
}
else{
if(n%2==0) return 1.0/(temp*temp);
else return 1.0/(temp*temp*x);
}
}
};