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

};
相关推荐
ZPC82101 天前
docker 镜像备份
人工智能·算法·fpga开发·机器人
ZPC82101 天前
docker 使用GUI ROS2
人工智能·算法·fpga开发·机器人
琢磨先生David1 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
颜酱1 天前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
多恩Stone1 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
生信大杂烩1 天前
癌症中的“细胞邻域“:解码肿瘤微环境的空间密码 ——Nature Cancer 综述解读
人工智能·算法
蜡笔小马2 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
m0_531237172 天前
C语言-数组练习进阶
c语言·开发语言·算法
超级大福宝2 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
qq_459234422 天前
【题库】| 商用密码应用安全性评估从业人员考核题库(四十)
职场和发展·密码学·学习方法·考核·商用密码·商用密码应用安全性评估·密评