Pow(x, n) 【新思路】

Implement pow(xn).

思路:这道题的关键在于 时间。想办法让时间复杂度降低。(但有一点我没想懂,不考虑大小溢出问题么?难道因为是double的原因?待我研究下)

解法很巧妙。想了好久,觉得这个解释更合理一点。

n = 2k+m  ----> xn = (x2)k·xm

数n可以拆分成2k+m  ,其中n<<k后仍大于0,表示xn中包含(x2)k ,m表示左移k次中的结果为奇数的次数。(好难想啊哎)

public:

    //caution: 1.need i consider double and int overflow ??????
    // time limit exceed!!!!
    double pow(double x, int n) {
        if(n<0) return 1/power(x,-n);
        else return power(x,n);
       
    }
    double power(double x, int n){
        double rel=1;
        while(n>0){
            if(n%2==1) rel=rel*x;
            n=n>>1;
            x=x*x;
        }
        return rel;
    }
};
原文地址:https://www.cnblogs.com/renrenbinbin/p/4337834.html