leetcode:Pow(x, n) (计算x的n次方)

2014-11-24 00:12:07 · 作者: · 浏览: 10
题目: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