【LeetCode 0050】【分治/递归】求x的n次方

  1. Pow(x, n)

Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).

Example 1:

复制代码
**Input:** x = 2.00000, n = 10
**Output:** 1024.00000

Example 2:

复制代码
**Input:** x = 2.10000, n = 3
**Output:** 9.26100

Example 3:

复制代码
**Input:** x = 2.00000, n = -2
**Output:** 0.25000
**Explanation:** 2^-2 = 1/2^2 = 1/4 = 0.25

Constraints:

  • -100.0 < x < 100.0
  • -2^31 <= n <= 2^31-1
  • n is an integer.
  • Either x is not zero or n > 0.
  • -10^4 <= x^n <= 10^4
Idea
text 复制代码
* 调库函数Math.pow(x,n)
* 暴力乘法
* 分治递归,一分为二
JavaScript Solution
javascript 复制代码
/**
 * @param {number} x
 * @param {number} n
 * @return {number}
 */
var myPow = function(x, n) {
    if( !n ){
        return 1
    }

    if( n < 0 ){
        return 1/myPow(x,-n)
    }

    if( n%2 ){
        return x*myPow(x,n-1)
    }
    return myPow(x*x, n/2 ); 

};
相关推荐
ychqsq2 分钟前
88.归途
经验分享·职场和发展
巧克力男孩dd37 分钟前
Python超典型练习题(第一次作业)
开发语言·python·算法
爱刷碗的苏泓舒1 小时前
平方根信息滤波:矩阵推导及 GNSS 参数估计应用
线性代数·算法·矩阵·gnss·参数估计·测量平差·平方根信息滤波
想做小南娘,发现自己是女生喵2 小时前
第 2 章 顺序表和 vector
java·数据结构·算法
艾醒2 小时前
2026年第29周(7.13-7.19)AI全复盘:技术突破、行业趣闻翻车、算力服务器商业动态
人工智能·算法
雪碧聊技术3 小时前
动态规划算法—01背包问题
算法·动态规划
bu_shuo3 小时前
c与cpp中的argc和argv
c语言·c++·算法
普贤莲花3 小时前
【2026年第29周---写于20260718】---整理,断舍离
程序人生·算法·生活
Reart3 小时前
Leetcode 674.最长连续递增序列 (719)
后端·算法
Reart3 小时前
Leetcode 300.最长递增子序列(719)
算法