JS算法之快速幂-数值的整数次方

var myPow = function (x, n) {
    let result = 1.0;
    //如果负数,2^-2可以变成(1/2)^2
    if (n < 0) {
        //js中默认不是整除
        x = 1 / x;
        n = -n;
    }
    while (n > 0) {
        if (n & 1) { // 如果n最右位是1,将当前x累乘到result
            result *= x;
        }
        x *= x; // x自乘法
        //>>是有符号数的移位,>>>是无符号数的移位
        //下面第一种是错误的,剩下两个都是正确的
        // n = n>>1
        // n = Math.floor(n/2)
        n = n >>> 1
    }
    console.log(result)
    // return result;
};
myPow(5, 2)

猜你喜欢

转载自blog.csdn.net/weixin_38128649/article/details/127064100