# 50. 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/22 = 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`

``````class Solution {
public:
double myPow(double x, int n) {
if (n == 0) return 1;
double half = myPow(x, n / 2);
if (n % 2 == 0) return half * half;
return n > 0 ? half * half * x : half * half / x;
}
};
``````

``````class Solution {
public:
double myPow(double x, int n) {
double res = 1.0;
for (int i = n; i != 0; i /= 2) {
if (i % 2 != 0) res *= x;
x *= x;
}
return n < 0 ? 1 / res : res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/50

Sqrt(x)

Super Pow

Count Collisions of Monkeys on a Polygon

https://leetcode.com/problems/powx-n/

https://leetcode.com/problems/powx-n/discuss/19733/simple-iterative-lg-n-solution

https://leetcode.com/problems/powx-n/discuss/19546/Short-and-easy-to-understand-solution

https://leetcode.com/problems/powx-n/discuss/19544/5-different-choices-when-talk-with-interviewers

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation