Intuition
Square the base repeatedly and multiply it into the result only for the set bits of the exponent. This computes x^n in O(log n) multiplications instead of n. Negative exponents just invert the base first.
Explanation
Idea
Computing x^n by multiplying n times is O(n). Instead, use the binary representation of n: x^n is the product of x^(2^k) for each set bit k. We repeatedly square x (giving x, x², x⁴, x⁸, …) and multiply the current square into the answer whenever the corresponding bit of n is 1.
A negative exponent is handled by replacing x with 1/x and negating n.
Algorithm
- If
n < 0, setx = 1/xandn = -n. result = 1. Whilen > 0:- If the lowest bit of
nis set,result *= x. - Square:
x *= x; shiftn >>= 1.
- If the lowest bit of
- Return
result.
Worked example: x = 2, n = 10 (binary 1010)
| bit | n | x (square) | result |
|---|---|---|---|
| 0 | 1010 | 2 | 1 |
| 1 | 101 | 4 | 4 |
| 0 | 10 | 16 | 4 |
| 1 | 1 | 256 | 1024 |
Result: 1024 (bits 1 and 3 of 10 are set → 4 × 256).
Complexity
- Time: O(log n).
- Space: O(1).
Implementation
class Solution {
public double myPow(double x, int n) {
long exp = n;
if (exp < 0) {
x = 1 / x;
exp = -exp;
}
double result = 1.0;
while (exp > 0) {
if ((exp & 1) == 1) {
result *= x;
}
x *= x;
exp >>= 1;
}
return result;
}
}