Pow(x, n) — LeetCode 50 Python Solution
MediumRecursionMath
- Problem
- #50
- Pattern
- Math and Number Theory
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(\log n) |
| Space | O(1) auxiliary |
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
On study lists
This problem is on NeetCode 150 and Top Interview 150.
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.