首页 > 代码库 > Pow(x, n)

Pow(x, n)

方法:采用分治的方法,x^n = x^n/2*x^n/2*x^n%2;

class Solution {
public:
    double myPow(double x, int n) {
        if(n < 0)
            return 1.0 / power(x, -n);
        else
            return power(x, n);
    }
    
    double power(double x, int n)
    {
        if( n == 0)
            return 1;
        double v = power(x, n/2);
        if(n%2 == 0)
            return v*v;
        else
            return v*v*x;
    }
};

 

Pow(x, n)