leetCode-Record icon indicating copy to clipboard operation
leetCode-Record copied to clipboard

面试题16. 数值的整数次方

Open fireairforce opened this issue 5 years ago • 0 comments

快速幂,徒手写就行了,判断一下正负即可:

/**
 * @param {number} x
 * @param {number} n
 * @return {number}
 */
var myPow = function(x, n) {
    let ans = 1;
    let flag = 0;
    if(n < 0) {
        n = -n;
        flag = 1;
    }
    while(n) {
        if(n % 2) {
            ans *= x; 
        }
        x *= x;
        n = Math.floor(n / 2);
    }
    return flag ? 1 / ans : ans;
};

fireairforce avatar Feb 19 '20 13:02 fireairforce