Pow(x, n) (LeetCode 50): Solution and Explanation
Compute x raised to the integer power n, where x is a floating point number and n can be negative, zero or positive, without calling a built-in power function.
Watch it run step by step
Try your own input and write the code →Intuition
The direct approach multiplies x by itself n times. That is O(n), and since n can be over two billion in magnitude, it is far too slow. The goal is to reuse work instead of redoing it.
The key fact is that powers can be squared. Once you know x to the 4th, squaring it gives x to the 8th in one multiplication instead of four. In general x to the 2m is the square of x to the m, and x to the 2m + 1 is that square times one more x. Halving the exponent at every step means only about log₂(n) steps are needed.
The iterative version reads this off the binary digits of n. Write n in binary, for example 10 is 1010, which means x to the 10th equals x to the 8th times x to the 2nd. Keep a variable that holds x, then x squared, then x to the 4th, and so on, by squaring it each round. Look at the lowest bit of n each round: if it is 1, multiply that current power into the result. Then shift n right by halving it. When n reaches 0, every set bit has contributed its power.
Negative exponents reduce to positive ones: x to the -n is 1 / x to the n. So the code flips x to its reciprocal and makes n positive before the loop. Zero is handled up front, since anything to the 0th power is 1.
Approach: Iterative exponentiation by squaring
- If
n == 0, return 1. - If
nis negative, replacexwith1 / xandnwith-n. - Start with
result = 1. - While
n > 0, ifnis odd, multiplyresultby the currentx, since this bit ofnis set. - Square
xso it represents the power for the next bit, and halvenwith integer division. - When
nreaches 0, returnresult.
Step-by-step example
x = 2.0, n = 10
nis 10, which is 1010 in binary. Start withresult = 1.n = 10is even, soresultstays 1. Squarexto 4 and halvento 5.n = 5is odd, soresult = 1 × 4 = 4. Squarexto 16 and halvento 2.n = 2is even, soresultstays 4. Squarexto 256 and halvento 1.n = 1is odd, soresult = 4 × 256 = 1024. Squarexand halvento 0.- The loop ends and the answer is 1024.0, which is 2 to the 10th.
Code: Python, Java, C++
1class Solution:
2 def myPow(self, x: float, n: int) -> float:
3 if n == 0:
4 return 1
5 if n < 0:
6 x = 1 / x
7 n = -n
8
9 result = 1
10 while n > 0:
11 if n % 2 == 1: # n is odd
12 result *= x
13 x *= x # Square x
14 n //= 2 # Halve n
15 return result1class Solution {
2 public double myPow(double x, int n) {
3 if (n == 0) return 1;
4
5 long N = n;
6 if (N < 0) {
7 x = 1 / x;
8 N = -N;
9 }
10
11 double result = 1;
12 while (N > 0) {
13 if (N % 2 == 1) {
14 result *= x;
15 }
16 x *= x;
17 N /= 2;
18 }
19 return result;
20 }
21}1class Solution {
2public:
3 double myPow(double x, int n) {
4 if (n == 0) return 1;
5
6 long long N = n;
7 if (N < 0) {
8 x = 1 / x;
9 N = -N;
10 }
11
12 double result = 1;
13 while (N > 0) {
14 if (N % 2 == 1) {
15 result *= x;
16 }
17 x *= x;
18 N /= 2;
19 }
20 return result;
21 }
22};Time and space complexity
O(log n)
Each iteration halves n, so the loop runs once per binary digit of n, which is about log₂(n) times, with constant work per iteration.
O(1)
Only x, n and result are updated in place. There is no recursion.
Other approaches
Recursive fast power (time O(log n), space O(log n))
Compute half = myPow(x, n // 2) and return half × half, multiplied by x once more if n is odd. It is the same idea top down and easy to derive, but it uses a call stack of depth log n.
Repeated multiplication (time O(n), space O(1))
Multiply the result by x exactly |n| times. It is correct and trivial but runs out of time for large exponents.
Common mistakes
- Negating
nin a fixed-width integer language. In Java or C++,-noverflows whennis the minimum 32-bit integer, so convertnto a 64-bitlongfirst. - Computing
myPow(x, n // 2) × myPow(x, n // 2)in a recursive version. Making two calls instead of reusing one result brings the time back to O(n). - Forgetting to invert
xfor negative exponents, which returns a huge number instead of a small fraction. - Relying on Python's
n // 2for negativen. It rounds toward negative infinity, which is why the code makesnpositive before the loop.
Frequently asked questions
Why is fast power O(log n)?
Each step halves the exponent and does at most two multiplications. An exponent of n can only be halved about log₂(n) times before it reaches 0.
How do you handle a negative exponent in Pow(x, n)?
Use the identity that x to the -n equals 1 / x to the n. Replace x with its reciprocal, make n positive, and run the normal algorithm.
Why does the Java solution cast n to long?
The smallest 32-bit integer has no positive counterpart, so negating it overflows back to itself. Storing n in a 64-bit variable before negating avoids that.
What should Pow(x, n) return when x is 0 and n is negative?
Mathematically that is a division by zero, so the result is undefined. The problem's constraints rule this case out, which is why the reference code does not guard against it. In production code you would raise an error or return infinity explicitly.