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.
ncan be negative, and can be as large as2³¹ - 1or as small as-2³¹.- With
nup to about two billion, multiplyingxby itselfntimes is far too slow. The answer must take aboutlog nsteps. - The inputs keep the answer between
-10⁴and10⁴.
- -100.0 < x < 100.0
- -2³¹ <= n <= 2³¹ - 1
- n is an integer.
- Either x is not zero or n > 0.
- -10⁴ <= xⁿ <= 10⁴
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)takeskmultiplications, not2^k. - Bits pick the squares: read
nfrom 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 flipxto1/xand makenpositive first.
This is called binary exponentiation, and it needs about 31 rounds for any 32-bit n.
Approach
Two ways to solve it
Square x each round and multiply it into the answer when the lowest bit of n is 1.
- Memory: two variables, no call stack.
- Idea: the bits of
nchoose which squares to use.
Compute x^(n/2) once, square it, and multiply by one more x when n is odd.
- Natural: follows
x^n = (x^(n/2))²directly. - Memory: about 32 stack frames.
Both take O(log n) time. The loop uses O(1) memory and avoids recursion, so the steps, code and live demo follow it; the recursive version is further down.
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.
Start the answer at 1
result = 1 is the empty product, so n = 0 returns 1 without ever entering the loop.
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.
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.
Code in Python, C++ and Java
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.
Common pitfalls
Negating n inside an int
if (n < 0) {
x = 1 / x;
n = -n;
}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
return myPow(x, n / 2) * myPow(x, n / 2)
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.
Edge cases
The loop never runs and the answer is 1, even for x = 0 (the constraints only rule out x = 0 with a negative n).
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.
Complexity
|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.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.