【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 ); 

};
相关推荐
产品经理邹继强8 小时前
VTC财务与投资篇②:预算革命——如何用三维算法决定每一分钱去哪
算法
Polaris北8 小时前
第二十四天打卡
算法
Anastasiozzzz8 小时前
G1垃圾回收流程详解
java·开发语言·算法
滴滴答滴答答9 小时前
LeetCode Hot100 之 17 有效的括号
算法·leetcode·职场和发展
掘根9 小时前
【C++STL】二叉搜索树(BST)
数据结构·c++·算法
老鼠只爱大米9 小时前
LeetCode经典算法面试题 #20:有效的括号(数组模拟法、递归消除法等五种实现方案详细解析)
算法·leetcode··括号匹配·数组模拟法·递归消除法
yxc_inspire9 小时前
2026年寒假牛客训练赛补题(五)
算法
不想看见4049 小时前
6.3Permutations -- 回溯法--力扣101算法题解笔记
笔记·算法·leetcode
诗词在线9 小时前
孟浩然诗作数字化深度实战:诗词在线的意象挖掘、检索优化与多场景部署
大数据·人工智能·算法
芜湖xin9 小时前
【题解-Acwing】113. 特殊排序
算法·插入排序·二分