Pow(x, n) — LeetCode 50 Python Solution

MediumRecursionMath
Problem
#50
Reading time
2 min

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

MeasureComplexity
TimeO(\log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview