快速幂

求解 x的n次方

class Solution {
public:
    double myPow(double x, int n) {
        if(n == 0 || x == 1)    return 1;
        double ans = 1;
        long k = n;
        if(k < 0){
            k = -k;
            x = 1/x;
        }
        while (k){
            if (k & 1) ans *= x; 
            k >>= 1;
            x = x * x;
        }               
        return ans;
    }
};

 

posted @ 2021-01-07 17:41  zeroPatrick  阅读(32)  评论(0编辑  收藏  举报