[leetcode] 50. Pow(x, n)

网友投稿 654 2022-11-08 19:00:31

[leetcode] 50. Pow(x, n)

Description

Implement pow(x, n), which calculates x raised to the power n (xn).

Example 1:

Input:

2.00000, 10

Output:

1024.00000

Example 2:

Input:

2.10000, 3

Output:

9.26100

Example 3:

Input:

2.00000, -2

Output:

0.25000

Explanation:

2-2 = 1/22 = 1/4 = 0.25

Note:

-100.0 < x < 100.0n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1]

分析

题目的意思是:实现pow(x, n)的功能。

递归,如果n为0,直接返回1;如果为负数,则需要变为正数的指数乘法;指数乘法利用x^n = (x(n/2))2这样可以减少迭代次数。

代码

class Solution {public: double myPow(double x, int n) { if(n<0){ return 1/power(x,-n); } return power(x,n); } double power(double x,int n){ if(n==0){ return 1; } if(n==INT_MIN){ return x*power(x,INT_MAX); } double half=power(x,n/2); if(n%2==1){ return half*half*x; }else{ return half*half; } }};

参考文献

​​[编程题]powx-n​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 238. Product of Array Except Self
下一篇:基于Jenkins+Maven+Gitea+Nexus搭建CICD环境的方式
相关文章