leetcode:Pow(x, n) (计算x的n次方) 【口试算法题】

leetcode:Pow(x, n) (计算x的n次方) 【面试算法题】题目:Implement pow(x, n).题意计算x的n次方,考虑复杂度

leetcode:Pow(x, n) (计算x的n次方) 【面试算法题】

题目:Implement pow(x, n).

题意计算x的n次方,考虑复杂度和n的取值。


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&1)return temp*temp*x;            else return temp*temp;        }        else         {            if(n&1)return 1.0/(temp*temp*x);            else return 1.0/(temp*temp);        }    }};// blog.csdn.net/havenoidea

题解目录