首页 > 代码库 > powx-n

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);       
    }
};

 

powx-n