MediumNo. 0050

Pow(x, n) — LeetCode 50 Python Solution

Topics
Recursion, Math
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

PythonSolution
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

Related problems
No.ProblemDifficulty
0060Permutation SequenceHard
0002Add Two NumbersMedium
0273Integer to English WordsHard
0326Power of ThreeEasy
0390Elimination GameMedium
1808Maximize Number of Nice DivisorsHard

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.

Free to download. Check it runs on your machine, then pick a plan.