LeetCode #50 Medium

Pow(x, n)

Pow(x, n) is LeetCode 50 (Medium). Implement pow(x, n): return x raised to the integer power n, where x is a double.

  • n can be negative, and can be as large as 2³¹ - 1 or as small as -2³¹.
  • With n up to about two billion, multiplying x by itself n times is far too slow. The answer must take about log n steps.
  • The inputs keep the answer between -10⁴ and 10⁴.
Constraints
  • -100.0 < x < 100.0
  • -2³¹ <= n <= 2³¹ - 1
  • n is an integer.
  • Either x is not zero or n > 0.
  • -10⁴ <= xⁿ <= 10⁴
mathrecursiondivide and conquer
Open on LeetCode ↗
02

Intuition

Write n in binary. 10 = 1010, so x^10 = x^8 · x^2. Any power is a product of the squares x, x², x⁴, x⁸, … whose bit in n is 1.

  • Squares are cheap: each one is the previous one times itself, so reaching x^(2^k) takes k multiplications, not 2^k.
  • Bits pick the squares: read n from its lowest bit up. A 1-bit multiplies the current square into the answer; a 0-bit skips it.
  • Negative n: x^(-n) = (1/x)^n, so flip x to 1/x and make n positive first.

This is called binary exponentiation, and it needs about 31 rounds for any 32-bit n.

03

Approach

1

Turn a negative exponent positive

If n < 0, set x = 1/x and n = -n. In C++ and Java copy n into a 64-bit long first, because -(-2³¹) does not fit in an int.

2

Start the answer at 1

result = 1 is the empty product, so n = 0 returns 1 without ever entering the loop.

3

Use the lowest bit of n

While n > 0, check n & 1. If it is 1, this round's square belongs in the answer, so multiply result by x. If it is 0, leave result alone.

4

Square x and shift n

Set x = x * x so it holds the next square, and shift n right by one so the next bit becomes the lowest. When n reaches 0 every bit has been used, and result is the answer.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def myPow(self, x: float, n: int) -> float:
▶3 if n < 0:
▶4 x = 1 / x
▶5 n = -n
▶6 result = 1.0
▶7 while n > 0:
▶8 if n & 1:
▶9 result *= x
▶10 x *= x
▶11 n >>= 1
▶12 return result
x^102x^21x^40x^81bit of nsquareresult1power 10 is 1010 in binary → 4 rounds
result1empty product
x2x^1
n10binary 1010
The answer starts at 1. The top row is 10 in binary, lowest bit on the right. Each column will hold one square of x, and only the columns with a 1 get multiplied into the answer.
x^102x^21x^40x^81bit of nsquareresult1bit is 0 → skip 2, answer stays 1
lowest bit0
result1unchanged
The lowest bit is 0, so 2^1 is not part of the answer. The result stays 1.
x^102x^214x^40x^81bit of nsquareresult1square x → 4, shift n right
x4now x^2
n5binary 101
Squaring turns 2^1 into 2^2 = 4 with one multiplication. Shifting n right drops the bit just used, so the next column's bit becomes the lowest.
x^102x^214x^40x^81bit of nsquareresult1×4=4bit is 1 → multiply the answer by 4
lowest bit1
result41 × 4
The lowest bit of what is left of n is 1, so this column's square, 4 (that is 2^2), is part of the answer. The result becomes 4.
x^102x^214x^4016x^81bit of nsquareresult4square x → 16, shift n right
x16now x^4
n2binary 10
Squaring turns 2^2 into 2^4 = 16 with one multiplication. Shifting n right drops the bit just used, so the next column's bit becomes the lowest.
x^102x^214x^4016x^81bit of nsquareresult4bit is 0 → skip 16, answer stays 4
lowest bit0
result4unchanged
The lowest bit is 0, so 2^4 is not part of the answer. The result stays 4.
x^102x^214x^4016x^81256bit of nsquareresult4square x → 256, shift n right
x256now x^8
n1binary 1
Squaring turns 2^4 into 2^8 = 256 with one multiplication. Shifting n right drops the bit just used, so the next column's bit becomes the lowest.
x^102x^214x^4016x^81256bit of nsquareresult4×256=1024bit is 1 → multiply the answer by 256
lowest bit1
result10244 × 256
The lowest bit of what is left of n is 1, so this column's square, 256 (that is 2^8), is part of the answer. The result becomes 1024.
x^102x^214x^4016x^81256bit of nsquareresult1024n shifts to 0 → no bits left, loop ends
x65536not needed any more
n0binary 0
The code squares x one last time, but n is now 0, so that square is never used. Every bit has been read.
x^102x^214x^4016x^81256bit of nsquareresult10242^10 = 1024 → return it
result1024
rounds4one per bit of 10
The answer is the product of the green squares: 2^10 = 1024. It took 4 rounds, one per bit of 10, rather than 10 separate multiplications.
05

Recursive halving

x^n is (x^(n/2))² when n is even and (x^(n/2))² · x when it is odd. Each call halves n, so there are about log n calls.

▶1class Solution:
▶2 def myPow(self, x: float, n: int) -> float:
▶3 if n < 0:
▶4 return 1 / self.myPow(x, -n)
▶5 if n == 0:
▶6 return 1.0
▶7 half = self.myPow(x, n // 2)
▶8 if n % 2 == 0:
▶9 return half * half
▶10 return half * half * x
06

Common pitfalls

Negating n inside an int

✗ Wrong
if (n < 0) {
    x = 1 / x;
    n = -n;
}
✓ Right
long e = n;
if (e < 0) {
    x = 1 / x;
    e = -e;
}

For n = -2³¹, -n overflows. In Java it stays -2³¹, the while (n > 0) loop never runs, and x = 2.0 returns 1.0 instead of 0.0. In C++ it is undefined behaviour.

Recursing on the half twice

✗ Wrong
return myPow(x, n / 2) * myPow(x, n / 2)
✓ Right
half = myPow(x, n // 2)
return half * half

Two calls per level double the work at every level, which adds back up to about n calls: n = 2³¹ - 1 times out. Compute the half once and square it.

07

Edge cases

n = 0

The loop never runs and the answer is 1, even for x = 0 (the constraints only rule out x = 0 with a negative n).

x < 0

The sign takes care of itself: x = -2, n = 3 multiplies in -2 and 4, giving -8. No special case for odd or even n.

08

Complexity

Time
O(log n)
Space
O(1)
One round per bit of |n|, so at most 32 rounds of two multiplications. The recursive version further down also takes O(log n) time, plus O(log n) stack.
09

Pow(x, n) FAQ

Can I just call the built-in pow or ** in an interview?

It is accepted, but the question exists to see you build the fast loop yourself. Mention the built-in, then write binary exponentiation.

How is this related to modular exponentiation?

It is the same loop with whole numbers and a % m after every multiplication, which keeps the values small. That version computes a^b mod m in O(log b) and is what Python's three-argument pow(a, b, m) does.