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

};
相关推荐
黄昏ivi1 小时前
电力系统最小惯性常数解析
算法
独家回忆3641 小时前
每日算法-250425
算法
烁3471 小时前
每日一题(小白)模拟娱乐篇33
java·开发语言·算法
Demons_kirit2 小时前
LeetCode 2799、2840题解
算法·leetcode·职场和发展
软行2 小时前
LeetCode 每日一题 2845. 统计趣味子数组的数目
数据结构·c++·算法·leetcode
永远在Debug的小殿下2 小时前
查找函数【C++】
数据结构·算法
我想进大厂2 小时前
图论---染色法(判断是否为二分图)
数据结构·c++·算法·深度优先·图论
油泼辣子多加2 小时前
【风控】稳定性指标PSI
人工智能·算法·金融
雾月553 小时前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
OpenC++4 小时前
【C++QT】Buttons 按钮控件详解
c++·经验分享·qt·leetcode·microsoft