leetcode New Year riots ward rehabilitation program 50. Pow (x, n) JS solution

/**
 * @param {number} x
 * @param {number} n
 * @return {number}
 */
function pow(x, n){
    var ans = 1;
    while(n){
        if(n % 2){
            years * = x;
        }
        x *= x;
        n >>= 1
    }
    return ans;
}
var myPow = function(x, n) {
    if(n == 0){
        return 1;
    }else if(n < 0){
        if(n == -2147483648){
            return 1 / (pow(x, 2147483647)*x);
        }else{
            return 1 / pow(x, -n);
        }
    }else{
        return pow(x, n);
    }
};

Fast power easily won only caveat is likely to exceed the upper limit of the need to deal with it when n is negative

Guess you like

Origin www.cnblogs.com/qq965921539/p/12231955.html