15% off all plans & roadmaps Use code

See plans

Pow(x, n)

Updated

TL;DR: Compute x raised to an integer power n, including negative n, without multiplying n times. Square the base and read the exponent's bits to finish in O(log |n|) multiplications.

Problem

Implement myPow(x, n), which returns x raised to the integer power n, that is x^n.

For a positive n, the answer is x multiplied by itself n times. For a negative n, the answer is the reciprocal of x raised to -n. When n is 0, return 1, even if x is not 1. Return the result as a floating-point number. The judge accepts answers with a relative error of at most 1e-5.

Example 1

Input: x = 1.5, n = 4
Output: 5.0625
Explanation: 1.5 * 1.5 * 1.5 * 1.5 = 5.0625.

Example 2

Input: x = 2, n = -3
Output: 0.125
Explanation: A negative exponent takes the reciprocal, so 2^-3 = 1 / 2^3 = 0.125.

Example 3

Input: x = -7, n = 0
Output: 1
Explanation: Any non-zero base raised to the zero power is 1.

Constraints

  • x is a floating-point number.
  • -2^31 <= n <= 2^31 - 1
  • x is non-zero or n > 0.
  • |x^n| <= 10^4
  • The answer is accepted if its relative error is at most 1e-5.

Constraints that matter

  • n can reach 2^31 in absolute value. Multiplying n times costs billions of steps, so you need O(log |n|) multiplications.
  • n can be -2^31. Its negation does not fit in a 32-bit int, so Java, C++ and C# need a 64-bit exponent before you negate.
  • x can be negative and n can be negative. Convert to a reciprocal base first, then work with a non-negative exponent only.
  • x is non-zero when n is negative, so 1 / x never divides by zero.
  • The answer tolerance is a relative 1e-5. Floating-point rounding from about 32 squarings is far below that, so no special precision tricks are needed.

View on LeetCode

Hints

Hint 1

This is exponentiation by squaring.

Hint 2

Multiply x into a running product |n| times.

Solution

Intuition

This is exponentiation by squaring. The exponent has a binary form, and every power of two in that form is reachable by squaring. For example 13 = 8 + 4 + 1, so x^13 = x^8 * x^4 * x^1. You never need 13 separate multiplications.

It is like paying a bill with denominations 1, 2, 4, 8 and so on. Each square of the base is the next denomination, and each set bit of the exponent means you hand over that bill into result.

Start with the base x, which stands for x^1. Squaring it gives x^2, squaring again gives x^4, then x^8, and so on. Each squaring is one multiplication and doubles the exponent. After k squarings you hold x^(2^k).

The bits of the exponent tell you which of those powers belong in the answer. If the lowest bit of the exponent is 1, multiply the current power into the result. Then shift the exponent right by one and square the base, so the next bit lines up with the next power.

Negative exponents reduce to the positive case: x^(-n) = (1 / x)^n. Flip the base once at the start and the loop only sees a non-negative exponent. The loop runs once per bit, so a 32-bit exponent needs at most 32 iterations.

Watch the pattern animation

Worked example

Input: x = -2, n = -2147483648
Output: 0
Explanation: The exponent is the smallest 32-bit integer. The true answer is 1 / (-2)^(2^31), which is a number so close to zero that a double stores it as 0. Any correct solution must also survive negating -2^31 without overflow.

Approach 1: Brute force

Multiply x into a running product |n| times. If n is negative, replace x with 1 / x first so the loop always counts up.

This is correct and takes a few lines. The code below adds three cheap guards so that the huge cases finish. It returns early when the base is 1 or -1, and when the product underflows to 0. These guards do not change the idea: the work is still one multiplication per unit of the exponent.

Steps

  1. If n is negative, set x = 1 / x and work with m = |n| stored in a 64-bit type.
  2. If x is 1, return 1. If x is -1, return -1 for odd m and 1 for even m.
  3. Set result = 1.0.
  4. Repeat m times: multiply result by x.
  5. If result becomes 0, return 0 because it has underflowed and can never recover.
  6. Return result.

Dry run

Take x = 2, n = 3 first. The product goes 1, 2, 4, 8, so three multiplications give 8.

Now the page's example, x = -2, n = -2147483648. The base becomes -0.5 and m becomes 2147483648. The product alternates sign and halves in size: -0.5, 0.25, -0.125, and so on.

After roughly 1,075 multiplications the magnitude drops below the smallest double, the product becomes 0, and the guard returns 0. Without that guard the loop would run over two billion times.

Any input where the product stays representable, such as x = 1.0000001, still pays one step per unit of |n|.

Complexity

TimeO(|n|)
SpaceO(1)

Let n be the exponent. The loop body runs once per unit of |n|, so it does at most |n| multiplications and no other work. With |n| up to 2^31 that is over two billion steps in the worst case, which is too slow. The only storage is result, x and a counter, so space is constant.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n < 0:
            x = 1.0 / x
        m = abs(n)
        if x == 1.0:
            return 1.0
        if x == -1.0:
            return -1.0 if m % 2 == 1 else 1.0
        result = 1.0
        for _ in range(m):
            result *= x
            if result == 0.0:  # underflowed, cannot recover
                return 0.0
        return result

Approach 2: Recursive squaring

What's slow: the brute force recomputes the same product over and over. Computing x^8 by eight multiplications ignores that x^8 is x^4 times x^4.

The insight that fixes it: split the exponent in half. If e is even, x^e = (x^(e/2))^2. If e is odd, x^e = (x^(e/2))^2 * x, using integer division.

You compute the half power once and square it. The exponent halves each call, so the recursion is about 32 levels deep.

Steps

  1. If n is negative, set x = 1 / x and e = -n in a 64-bit type.
  2. Define power(b, e). If e is 0, return 1.
  3. Compute half = power(b, e / 2) once, never twice.
  4. If e is even, return half * half.
  5. If e is odd, return half * half * b.
  6. Return power(x, e) from myPow.

Dry run

Take x = 2, n = 13. The calls go 13, 6, 3, 1, 0. Unwinding: power(0) = 1. power(1) = 112 = 2. power(3) = 222 = 8. power(6) = 88 = 64. power(13) = 6464*2 = 8192.

On the page's example the base becomes -0.5 and e = 2^31. The calls halve down to e = 1, which returns -0.5. Then each level squares: e=2 gives 2^-2, e=4 gives 2^-4, e=8 gives 2^-8, and the exponent of 2 doubles each level.

At e=1024 the value is 2^-1024, still representable as a subnormal. At e=2048 it would be 2^-2048, which underflows to 0. Every higher level squares 0 and returns 0, so the final answer is 0.

Complexity

TimeO(log |n|)
SpaceO(log |n|)

Let n be the exponent. Each call makes one recursive call with e / 2, so the depth is about log2(|n|) + 1, which is at most 32 for a 32-bit exponent. Each level does at most two multiplications, so time is O(log |n|). The call stack holds one frame per level, so space is O(log |n|).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def myPow(self, x: float, n: int) -> float:
        def power(b: float, e: int) -> float:
            if e == 0:
                return 1.0
            half = power(b, e // 2)  # compute the half power once
            if e % 2 == 0:
                return half * half
            return half * half * b

        if n < 0:
            x = 1.0 / x
            n = -n
        return power(x, n)
Bitwise Operations - Power of Two/Four Check pattern infographic for Pow(x, n)

Solution pattern

Bitwise Operations - Power of Two/Four Check

Part of Bit Manipulation Patterns

Approach 3: Iterative bit loopOptimalBitwise Operations - Power of Two/Four Check

What's slow: the recursive version is fast in time, but it uses a call stack of about 32 frames and does the work on the way back up. That stack is avoidable.

The insight that fixes it: run the same idea from the lowest bit upward. Keep result, the current power x, and the remaining exponent e. If e is odd, multiply x into result. Then square x and shift e right by one.

When e reaches 0, every bit has been used and result is the answer. This needs three scalars and no recursion.

Why it is correct. The invariant is that result times x to the power e always equals the original x to the power n. It starts true since result is 1 and e is n, and each step keeps it true, so e = 0 leaves result as the answer. Odd e moves one factor of x into result, and halving e with squaring keeps the rest equal.

Steps

  1. Store n in a 64-bit e. If e is negative, set x = 1 / x and e = -e.
  2. Set result = 1.0.
  3. While e > 0, test the lowest bit with e & 1.
  4. If the bit is 1, multiply result by the current x.
  5. Square x, so it moves from x^(2^k) to x^(2^(k+1)).
  6. Shift e right by one to drop the bit you just used.
  7. Return result. When n is 0 the loop never runs and result is 1.

Dry run

Start with x = -2, n = -2147483648. The exponent is negative, so x becomes -0.5 and e becomes 2^31, whose binary form is a 1 followed by 31 zeros. Only the top bit is set. Initial state: result = 1, x = -0.5, e = 2^31.

IterationLowest bit of eresultx after squaringe after shift
1012^-22^30
2012^-42^29
3012^-82^28
4012^-162^27
5012^-322^26
6012^-642^25
7012^-1282^24
8012^-2562^23
9012^-5122^22
10012^-10242^21
11010 (2^-2048 underflows)2^20
12 to 31010down to 1
3211 * 0 = 000

The loop ends because e is 0, and the function returns 0. For a smaller check, x = 2, n = 13 (binary 1101) multiplies in 2, skips 4, then multiplies in 16 and 256, giving 2 * 16 * 256 = 8192.

Complexity

TimeO(log |n|)
SpaceO(1)

Let n be the exponent. Each iteration shifts e right by one, so the loop runs once per bit of |n|, which is at most 32 for a 32-bit input. Each iteration does at most two multiplications and one shift. The loop keeps only result, x and e, so space is constant.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n < 0:
            x = 1.0 / x
            n = -n

        result = 1.0
        while n > 0:
            if n & 1:       # this bit of the exponent is set
                result *= x
            x *= x          # x becomes the next power of two power
            n >>= 1
        return result

Common mistakes

  • Writing n = -n on a 32-bit int in Java, C++ or C#. The value -2^31 has no positive counterpart, so it overflows. Copy n into a long or long long before you negate.
  • Negating the exponent but leaving x unchanged for negative n. That returns x^|n| instead of its reciprocal. Set x = 1.0 / x in the same branch.
  • Squaring x in the wrong place or skipping the squaring. Without x *= x every set bit multiplies the same power of the base. Square once per iteration, after the bit test.
  • Initialising result = x instead of 1.0. This returns x for n = 0 and adds one extra factor otherwise. 1.0 is the multiplicative identity.
  • In the recursive version, writing power(b, e / 2) * power(b, e / 2). That calls the function twice per level and brings the cost back to O(|n|). Store the half result in a variable and square it.
  • In JavaScript, using n >> 1 or n & 1 on 2^31. Bitwise operators convert to a 32-bit signed value, so 2^31 turns negative and the loop breaks. Use n % 2 and Math.floor(n / 2).

Edge cases

  • n = 0 with any non-zero x, such as x = -7: return 1. The loop never runs.
  • n = -2147483648 with |x| > 1, such as x = -2: the answer underflows to 0. Your code must not overflow when negating.
  • n = 2147483647 with x = 1: the answer is 1. The loop finishes in 31 iterations.
  • x = -1 with a huge odd n: the answer is -1, and with an even n it is 1. Squaring keeps the magnitude at 1.
  • n = 1 or n = -1: return x or 1 / x. One iteration handles it.
  • x = 0 with positive n: return 0. The constraints rule out x = 0 with negative n, so 1 / x is safe.

Follow-ups interviewers ask

Why does the loop work for any exponent, and how would you prove it?
Use an invariant. At the start of each iteration, result * x^e equals the original base raised to the original exponent. If e is odd, moving one factor of x into result keeps the product the same. Squaring x and halving e keeps it the same too, because (x^2)^(e/2) = x^e for even e. When e hits 0, result alone equals the answer.
Can you avoid the reciprocal and handle negative n differently?
Yes. Compute x^|n| with the same loop, then return 1 / result at the end. The catch is overflow: with x = 2, n = -2^31 the positive power overflows to infinity before you invert it, and 1 / infinity is 0, which happens to be right. Inverting the base first avoids reasoning about that. Both work for the stated constraints.
How would you compute x^n modulo m for integers, and does the same code work?
The loop is the same, with result = result * x % m and x = x * x % m. Keep every intermediate value below m so the product fits in a 64-bit integer when m is up to about 3 * 10^9. This is modular exponentiation, and it is why the technique appears in cryptography and combinatorics problems. For a negative exponent you need a modular inverse instead of 1 / x.

Pow(x, n) FAQ

What is the time complexity of Pow(x, n)?

The optimal solution runs in O(log |n|) time, because the exponent halves every iteration and a 32-bit exponent has at most 32 bits. The brute force that multiplies n times is O(|n|), which is up to about 2 billion steps. Space is O(1) for the iterative loop and O(log |n|) for the recursive one.

Why use exponentiation by squaring for Pow(x, n)?

Squaring doubles the exponent in one multiplication, so you reach x^(2^k) in k steps. Any exponent is a sum of distinct powers of two, so you multiply in only the powers whose bit is set. That turns n multiplications into about log2(n).

How do I handle a negative exponent in LeetCode 50?

Replace x with 1 / x and the exponent with its absolute value, then run the normal loop. This works because x^(-n) = (1 / x)^n. Do the negation on a 64-bit integer so that n = -2^31 does not overflow.

Can Pow(x, n) be solved in O(1) extra space?

Yes. The iterative bit loop keeps only result, x and the exponent, so extra space is constant. The recursive version needs O(log |n|) stack space, about 32 frames at most.

What is the difference between the recursive and iterative solutions in Python?

Both do O(log |n|) multiplications. The recursive one is shallow, about 32 calls, so Python's recursion limit is not a concern here. The iterative one avoids the call overhead and the stack. Python integers never overflow, so the minimum exponent needs no special handling in Python.

Why does Pow(x, n) return 0 for x = -2 and n = -2147483648?

The true value is 1 / 2^2147483648, which is far below the smallest positive double, about 4.9 * 10^-324. The repeated squaring of the base -0.5 underflows to 0 after 11 squarings, and the result then multiplies by 0. That matches the expected output of 0.

Asked at

See which companies ask this — Pro

Practise it