这真的考数学。。。

var myPow = function(x, n) {
    if (n===0) return 1;
    
    let pow = Math.abs(n);
    
	let result = pow%2===0 ? myPow(x*x,pow/2) : myPow(x*x,(pow-1)/2) * x;
    
    return n < 0 ? 1/result : result;

};

另一种看起来简洁的


var myPow = function(x, n) {
    if(n < 0){
        x = 1/x;
        n = -n;
    }

    let result = 1;
    while(n !== 0){
        if(n % 2 !== 0){
            result = result * x;
        }
        x = x * x;
        n = Math.floor(n / 2);
    }
    return result;
};

分类:

技术点:

相关文章: