数值的整数次方(快速幂)

思路:原本需要算n次,依次算x1,x2,...,x^n,时间复杂度O(n),现在只需要算一半就行

class Solution {
    public double myPow(double x, int n) {
        if(x == 0) return 0;
        long b = n;
        double res = 1.0;
        if(b < 0) {
            x = 1 / x;
            b = -b;
        }
        while(b > 0) {
            if((b & 1) == 1) res *= x;
            x *= x;
            b >>= 1;
        }
        return res;
    }
}

链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/solution/mian-shi-ti-16-shu-zhi-de-zheng-shu-ci-fang-kuai-s/

posted @ 2020-04-16 21:29  程序员小宇  阅读(209)  评论(0编辑  收藏  举报