1684838553 / arithmeticQuestions

程序员的算法趣题
2 stars 0 forks source link

Pow(x, n) #10

Open 1684838553 opened 2 years ago

1684838553 commented 2 years ago

50. Pow(x, n) 实现 pow(x, n) ,即计算 x 的整数 n 次幂函数(即,xn )。

示例 1:

输入:x = 2.00000, n = 10 输出:1024.00000 示例 2:

输入:x = 2.10000, n = 3 输出:9.26100 示例 3:

输入:x = 2.00000, n = -2 输出:0.25000 解释:2-2 = 1/22 = 1/4 = 0.25

1684838553 commented 2 years ago
/**
 * @param {number} x
 * @param {number} n
 * @return {number}
 */
var myPow = function(x, n) {
    if(n === 0){
        return 1
    }else if(n === 1){
        return x
    }else if(n < 0){
        return myPow(1/x,Math.abs(n))
    } else if(n %2===0){
        return myPow(x*x,n/2)
    } else{
        return myPow(x * x ,Math.floor(n/2))* x
    }
};