MediumNo. 0050
Pow(x, n) — LeetCode 50 Python Solution
- Pattern
- Math and Number Theory
- Topics
- Recursion, Math
- On study lists
- NeetCode 150 and Top Interview 150
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Example
- Input
- x = 2.00000, n = 10
- Output
- 1024.00000
Python solution
class Solution:
def myPow(self, x: float, n: int) -> float:
def qpow(a: float, n: int) -> float:
ans = 1
while n:
if n & 1:
ans *= a
a *= a
n >>= 1
return ans
return qpow(x, n) if n >= 0 else 1 / qpow(x, -n)Complexity
- Time
- O(log n)
- Space · auxiliary
- O(1)
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 50. Pow(x, n) is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0060 | Permutation Sequence | Hard |
| 0002 | Add Two Numbers | Medium |
| 0273 | Integer to English Words | Hard |
| 0326 | Power of Three | Easy |
| 0390 | Elimination Game | Medium |
| 1808 | Maximize Number of Nice Divisors | Hard |
Frequently asked questions
- How hard is LeetCode 50. Pow(x, n)?
LeetCode 50. Pow(x, n) is rated Medium on LeetCode.
- What is the time complexity of LeetCode 50. Pow(x, n)?
The Python solution on this page runs in O(log n).
- What is the space complexity of LeetCode 50. Pow(x, n)?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 50. Pow(x, n) cover?
LeetCode 50. Pow(x, n) is tagged Recursion and Math on LeetCode.