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

};
相关推荐
hqyjzsb13 小时前
法律 Prompt 干货:搭建合同审查提示词要包含哪些要素
开发语言·人工智能·python·职场和发展·数据分析·prompt·业界资讯
Discipline102914 小时前
尼泊尔河流流量:天气驱动的预测与高流量风险
人工智能·算法
XuCoder14 小时前
改一个数,右边全得重算,这题怎么扛住两万次查询
算法
小羊没烦恼!14 小时前
在Scrum中实施敏捷建模
java·开发语言·windows·算法·c#
weixin_3077791314 小时前
基于睿擎工业开发平台的预训练视觉模型轻量化适配与低代码部署优化
开发语言·算法
hold?fish:palm15 小时前
45 二叉树的右视图
开发语言·c++·算法
粤鼎恒业15 小时前
惠州工厂电子料回收厂家推荐:从交接单反推筛选标准
大数据·数据库·算法·硬件架构·硬件工程·pcb工艺·材料工程
小爷毛毛(卓寿杰)16 小时前
【Agent 意图识别】输出协议、评估与置信度
人工智能·算法·大模型·prompt·大语言模型·agent
优质酸酸乳16 小时前
力扣100题之21合并两个有序链表
算法·leetcode·链表
旖旎夜光16 小时前
LeetCode 137 : 只出现一次的数字 II(位运算) —— 题解
c++·笔记·学习·算法·leetcode·力控