powx-n

Implement pow(x, n).

//考虑一下情况:1.n<0 ;用暴力法会超时,所以这里用递归

class Solution {
public:
    double help(double x, int n)
    {
        if (n == 0)
            return 1;
            
        double tmp = help(x, n / 2);
            
        if (n % 2 == 0)
            return tmp * tmp;
        else
            return tmp * tmp * x;
    }
    
    double pow(double x, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (n < 0)
            return 1.0 / help(x, -n);
        else
            return help(x, n);       
    }
};

 

posted on 2017-03-08 17:35  123_123  阅读(110)  评论(0编辑  收藏  举报