Pow(x, n)
Pattern: Maths basics
Raise x to the power n in about log n multiplications by squaring x and reading n one bit at a time.
The problem
You are given a decimal number x (between -100 and 100) and a 32-bit integer n, which may be negative. Return x
raised to the power n. A negative power means one over the positive power, so 2 to the power -2 is 1/4 = 0.25. The
inputs are chosen so the answer stays within a normal decimal number's range.
The function name myPow matches LeetCode. Use the link above for the exact statement.
Think first
- How many multiplications does 2¹⁰ take if you multiply one 2 at a time? What about 2 to the power 2 billion?
- 2¹⁰ = (2²)⁵. And 2⁵ = 2 × 2⁴. Can you keep splitting like that?
- What should happen when
nis negative? And when it is the most negative 32-bit value?
Hints
Brute force, and why it fails
Multiply result by x exactly |n| times. That is correct, but for n near 2 billion it is 2 billion
multiplications, several seconds of work, and too slow on a judge. A recursive version that does x × pow(x, n - 1) is
worse: it also needs 2 billion nested calls and overflows the call stack.
The key insight
Squaring doubles the exponent in one multiplication. By squaring x and using the squares that match the 1 bits of
n, any power takes about log₂ n steps: 31 or 32 rounds for any 32-bit n.
Dry run
| power | 10 |
|---|---|
| x | 2 |
| result | 1 |
x = 2 and n = 10. n is not negative. result starts at 1. In binary 10 is 1010, shown in the array. We read it from the right.
The plan
power = n # stored in 64 bits, so -n cannot overflow
if power < 0:
x = 1 / x
power = -power
result = 1
while power > 0:
if power mod 2 == 1: # the lowest bit is 1
result = result * x
x = x * x # x stands for the next power of two
power = power div 2 # move on to the next bit
return result
Complexity
- Time
O(log n)- Space
O(1)
The power halves every round, so there are about 32 rounds for any 32-bit n. The loop keeps only three variables.
Edge cases
n = 0returns 1, because the loop does not run.- Negative powers: 2 to the power -2 is 0.25.
n = -2147483648: negating it needs 64 bits. Withx = 2the answer is so small it rounds to 0.x = 1orx = -1with a hugenstay 1 or ±1. The sign depends on whethernis odd.x = 0with a positivenis 0.
I've built my logic, show the code
Java
class Solution {
public double myPow(double x, int n) {
long power = n;
if (power < 0) {
x = 1 / x;
power = -power;
}
double result = 1;
while (power > 0) {
if (power % 2 == 1) {
result = result * x;
}
x = x * x;
power = power / 2;
}
return result;
}
}C++
class Solution {
public:
double myPow(double x, int n) {
long long power = n;
if (power < 0) {
x = 1 / x;
power = -power;
}
double result = 1;
while (power > 0) {
if (power % 2 == 1) {
result = result * x;
}
x = x * x;
power = power / 2;
}
return result;
}
};Python
class Solution:
def myPow(self, x: float, n: int) -> float:
power = n
if power < 0:
x = 1 / x
power = -power
result = 1.0
while power > 0:
if power % 2 == 1:
result = result * x
x = x * x
power = power // 2
return resultCommon mistakes
- Negating
nin a 32-bit int.-(-2147483648)overflows back to -2147483648. - Forgetting to multiply into the result when the power is odd, which loses factors.
- Recursing on
n - 1instead ofn / 2, which is still linear and overflows the stack. - Squaring the result instead of
x.