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

};
相关推荐
文丑颜不良啊7 分钟前
LeetCode2061~2080题目解析
java·leetcode
octopus_c1 小时前
STL 之 string:auto 与范围 for、常用接口、模拟实现与深浅拷贝
开发语言·c++·算法
文丑颜不良啊12 小时前
LeetCode1941~1960题目解析
java·leetcode
MUSHANGXS15 小时前
大模型时代的新蓝海-基于OS底层的AI-Agent应用
人工智能·职场和发展·交互
老师我太想进步了202616 小时前
【数据结构-4】算法美学之顺序表
数据结构·算法
风影同志7832416 小时前
编码器是激活函数吗?—— 一个看起来很像、其实不是的类比
算法
UIU11416 小时前
P1481 魔族密码
c++·算法·动态规划
文丑颜不良啊17 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊18 小时前
LeetCode2001~2020题目解析
java·leetcode