Ruby's Louvre

每天学习一点点算法

导航

leetcode 50. Pow(x, n)

这真的考数学。。。

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;
};

posted on 2019-12-15 21:21  司徒正美  阅读(307)  评论(0编辑  收藏  举报