LeetCode Day39 pow(x, n).

若简单的让x循环乘自己n次,则会超时
每次求一半次幂,加快速度

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

迭代:

class Solution {
public:
    double myPow(double x, int n) {
        double res=1.0;
        for(int i=n;i!=0;i/=2){
            if(i%2!=0) res*=x;
            x*=x; 
        }
        return n<0?1/res:res;      
    }
};

用原函数

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

猜你喜欢

转载自blog.csdn.net/weixin_41394379/article/details/84259381