15% off all plans & roadmaps Use code
See plansPow(x, n)
Updated
TL;DR: Compute x raised to an integer power n, including negative n, without multiplying n times. Square the base and read the exponent's bits to finish in O(log |n|) multiplications.
Problem
Implement myPow(x, n), which returns x raised to the integer power n, that is x^n.
For a positive n, the answer is x multiplied by itself n times. For a negative n, the answer is the reciprocal of x raised to -n. When n is 0, return 1, even if x is not 1. Return the result as a floating-point number. The judge accepts answers with a relative error of at most 1e-5.
Example 1
Input: x = 1.5, n = 4 Output: 5.0625 Explanation: 1.5 * 1.5 * 1.5 * 1.5 = 5.0625.
Example 2
Input: x = 2, n = -3 Output: 0.125 Explanation: A negative exponent takes the reciprocal, so 2^-3 = 1 / 2^3 = 0.125.
Example 3
Input: x = -7, n = 0 Output: 1 Explanation: Any non-zero base raised to the zero power is 1.
Constraints
xis a floating-point number.-2^31 <= n <= 2^31 - 1xis non-zero orn > 0.|x^n| <= 10^4- The answer is accepted if its relative error is at most
1e-5.
Constraints that matter
ncan reach 2^31 in absolute value. Multiplying n times costs billions of steps, so you need O(log |n|) multiplications.ncan be-2^31. Its negation does not fit in a 32-bitint, so Java, C++ and C# need a 64-bit exponent before you negate.xcan be negative andncan be negative. Convert to a reciprocal base first, then work with a non-negative exponent only.xis non-zero whennis negative, so1 / xnever divides by zero.- The answer tolerance is a relative 1e-5. Floating-point rounding from about 32 squarings is far below that, so no special precision tricks are needed.
Hints
Hint 1
This is exponentiation by squaring.
Hint 2
Multiply x into a running product |n| times.
Solution
Intuition
This is exponentiation by squaring. The exponent has a binary form, and every power of two in that form is reachable by squaring. For example 13 = 8 + 4 + 1, so x^13 = x^8 * x^4 * x^1. You never need 13 separate multiplications.
It is like paying a bill with denominations 1, 2, 4, 8 and so on. Each square of the base is the next denomination, and each set bit of the exponent means you hand over that bill into result.
Start with the base x, which stands for x^1. Squaring it gives x^2, squaring again gives x^4, then x^8, and so on. Each squaring is one multiplication and doubles the exponent. After k squarings you hold x^(2^k).
The bits of the exponent tell you which of those powers belong in the answer. If the lowest bit of the exponent is 1, multiply the current power into the result. Then shift the exponent right by one and square the base, so the next bit lines up with the next power.
Negative exponents reduce to the positive case: x^(-n) = (1 / x)^n. Flip the base once at the start and the loop only sees a non-negative exponent. The loop runs once per bit, so a 32-bit exponent needs at most 32 iterations.
Worked example
Input: x = -2, n = -2147483648 Output: 0 Explanation: The exponent is the smallest 32-bit integer. The true answer is 1 / (-2)^(2^31), which is a number so close to zero that a double stores it as 0. Any correct solution must also survive negating -2^31 without overflow.
Approach 1: Brute force
Multiply x into a running product |n| times. If n is negative, replace x with 1 / x first so the loop always counts up.
This is correct and takes a few lines. The code below adds three cheap guards so that the huge cases finish. It returns early when the base is 1 or -1, and when the product underflows to 0. These guards do not change the idea: the work is still one multiplication per unit of the exponent.
Steps
- If
nis negative, setx = 1 / xand work withm = |n|stored in a 64-bit type. - If
xis 1, return 1. Ifxis -1, return -1 for oddmand 1 for evenm. - Set
result = 1.0. - Repeat
mtimes: multiplyresultbyx. - If
resultbecomes 0, return 0 because it has underflowed and can never recover. - Return
result.
Dry run
Take x = 2, n = 3 first. The product goes 1, 2, 4, 8, so three multiplications give 8.
Now the page's example, x = -2, n = -2147483648. The base becomes -0.5 and m becomes 2147483648. The product alternates sign and halves in size: -0.5, 0.25, -0.125, and so on.
After roughly 1,075 multiplications the magnitude drops below the smallest double, the product becomes 0, and the guard returns 0. Without that guard the loop would run over two billion times.
Any input where the product stays representable, such as x = 1.0000001, still pays one step per unit of |n|.
Complexity
| Time | O(|n|) |
|---|---|
| Space | O(1) |
Let n be the exponent. The loop body runs once per unit of |n|, so it does at most |n| multiplications and no other work. With |n| up to 2^31 that is over two billion steps in the worst case, which is too slow. The only storage is result, x and a counter, so space is constant.
PythonTested in our runner
from typing import List, Optional
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
x = 1.0 / x
m = abs(n)
if x == 1.0:
return 1.0
if x == -1.0:
return -1.0 if m % 2 == 1 else 1.0
result = 1.0
for _ in range(m):
result *= x
if result == 0.0: # underflowed, cannot recover
return 0.0
return result
JavaTested in our runner
import java.util.*;
class Solution {
public double myPow(double x, int n) {
long m = n;
if (m < 0) {
x = 1.0 / x;
m = -m; // safe in a long
}
if (x == 1.0) return 1.0;
if (x == -1.0) return m % 2 == 1 ? -1.0 : 1.0;
double result = 1.0;
for (long i = 0; i < m; i++) {
result *= x;
if (result == 0.0) return 0.0; // underflowed
}
return result;
}
}
C++Tested in our runner
class Solution {
public:
double myPow(double x, int n) {
long long m = n;
if (m < 0) {
x = 1.0 / x;
m = -m; // safe in long long
}
if (x == 1.0) return 1.0;
if (x == -1.0) return m % 2 == 1 ? -1.0 : 1.0;
double result = 1.0;
for (long long i = 0; i < m; i++) {
result *= x;
if (result == 0.0) return 0.0; // underflowed
}
return result;
}
};
JavaScriptTested in our runner
/**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function(x, n) {
if (n < 0) x = 1 / x;
const m = Math.abs(n);
if (x === 1) return 1;
if (x === -1) return m % 2 === 1 ? -1 : 1;
let result = 1;
for (let i = 0; i < m; i++) {
result *= x;
if (result === 0) return 0; // underflowed
}
return result;
};
GoTested in our runner
func myPow(x float64, n int) float64 {
m := int64(n)
if m < 0 {
x = 1.0 / x
m = -m
}
if x == 1.0 {
return 1.0
}
if x == -1.0 {
if m%2 == 1 {
return -1.0
}
return 1.0
}
result := 1.0
for i := int64(0); i < m; i++ {
result *= x
if result == 0 {
return 0.0 // underflowed
}
}
return result
}
C#Tested in our runner
public class Solution {
public double myPow(double x, int n) {
long m = n;
if (m < 0) {
x = 1.0 / x;
m = -m; // safe in a long
}
if (x == 1.0) return 1.0;
if (x == -1.0) return m % 2 == 1 ? -1.0 : 1.0;
double result = 1.0;
for (long i = 0; i < m; i++) {
result *= x;
if (result == 0.0) return 0.0; // underflowed
}
return result;
}
}
Approach 2: Recursive squaring
What's slow: the brute force recomputes the same product over and over. Computing x^8 by eight multiplications ignores that x^8 is x^4 times x^4.
The insight that fixes it: split the exponent in half. If e is even, x^e = (x^(e/2))^2. If e is odd, x^e = (x^(e/2))^2 * x, using integer division.
You compute the half power once and square it. The exponent halves each call, so the recursion is about 32 levels deep.
Steps
- If
nis negative, setx = 1 / xande = -nin a 64-bit type. - Define
power(b, e). Ifeis 0, return 1. - Compute
half = power(b, e / 2)once, never twice. - If
eis even, returnhalf * half. - If
eis odd, returnhalf * half * b. - Return
power(x, e)frommyPow.
Dry run
Take x = 2, n = 13. The calls go 13, 6, 3, 1, 0. Unwinding: power(0) = 1. power(1) = 112 = 2. power(3) = 222 = 8. power(6) = 88 = 64. power(13) = 6464*2 = 8192.
On the page's example the base becomes -0.5 and e = 2^31. The calls halve down to e = 1, which returns -0.5. Then each level squares: e=2 gives 2^-2, e=4 gives 2^-4, e=8 gives 2^-8, and the exponent of 2 doubles each level.
At e=1024 the value is 2^-1024, still representable as a subnormal. At e=2048 it would be 2^-2048, which underflows to 0. Every higher level squares 0 and returns 0, so the final answer is 0.
Complexity
| Time | O(log |n|) |
|---|---|
| Space | O(log |n|) |
Let n be the exponent. Each call makes one recursive call with e / 2, so the depth is about log2(|n|) + 1, which is at most 32 for a 32-bit exponent. Each level does at most two multiplications, so time is O(log |n|). The call stack holds one frame per level, so space is O(log |n|).
PythonTested in our runner
from typing import List, Optional
class Solution:
def myPow(self, x: float, n: int) -> float:
def power(b: float, e: int) -> float:
if e == 0:
return 1.0
half = power(b, e // 2) # compute the half power once
if e % 2 == 0:
return half * half
return half * half * b
if n < 0:
x = 1.0 / x
n = -n
return power(x, n)
JavaTested in our runner
import java.util.*;
class Solution {
public double myPow(double x, int n) {
long e = n;
if (e < 0) {
x = 1.0 / x;
e = -e; // safe in a long
}
return power(x, e);
}
private double power(double b, long e) {
if (e == 0) return 1.0;
double half = power(b, e / 2); // compute the half power once
return e % 2 == 0 ? half * half : half * half * b;
}
}
C++Tested in our runner
class Solution {
public:
double myPow(double x, int n) {
long long e = n;
if (e < 0) {
x = 1.0 / x;
e = -e; // safe in long long
}
return power(x, e);
}
private:
double power(double b, long long e) {
if (e == 0) return 1.0;
double half = power(b, e / 2); // compute the half power once
return e % 2 == 0 ? half * half : half * half * b;
}
};
JavaScriptTested in our runner
/**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function(x, n) {
const power = (b, e) => {
if (e === 0) return 1;
const half = power(b, Math.floor(e / 2)); // compute once
return e % 2 === 0 ? half * half : half * half * b;
};
if (n < 0) {
x = 1 / x;
n = -n;
}
return power(x, n);
};
GoTested in our runner
func powRec(b float64, e int64) float64 {
if e == 0 {
return 1.0
}
half := powRec(b, e/2) // compute the half power once
if e%2 == 0 {
return half * half
}
return half * half * b
}
func myPow(x float64, n int) float64 {
e := int64(n)
if e < 0 {
x = 1.0 / x
e = -e
}
return powRec(x, e)
}
C#Tested in our runner
public class Solution {
public double myPow(double x, int n) {
long e = n;
if (e < 0) {
x = 1.0 / x;
e = -e; // safe in a long
}
return Power(x, e);
}
private double Power(double b, long e) {
if (e == 0) return 1.0;
double half = Power(b, e / 2); // compute the half power once
return e % 2 == 0 ? half * half : half * half * b;
}
}

Solution pattern
Bitwise Operations - Power of Two/Four Check
Part of Bit Manipulation Patterns
Approach 3: Iterative bit loopOptimalBitwise Operations - Power of Two/Four Check
What's slow: the recursive version is fast in time, but it uses a call stack of about 32 frames and does the work on the way back up. That stack is avoidable.
The insight that fixes it: run the same idea from the lowest bit upward. Keep result, the current power x, and the remaining exponent e. If e is odd, multiply x into result. Then square x and shift e right by one.
When e reaches 0, every bit has been used and result is the answer. This needs three scalars and no recursion.
Why it is correct. The invariant is that result times x to the power e always equals the original x to the power n. It starts true since result is 1 and e is n, and each step keeps it true, so e = 0 leaves result as the answer. Odd e moves one factor of x into result, and halving e with squaring keeps the rest equal.
Steps
- Store
nin a 64-bite. Ifeis negative, setx = 1 / xande = -e. - Set
result = 1.0. - While
e > 0, test the lowest bit withe & 1. - If the bit is 1, multiply
resultby the currentx. - Square
x, so it moves from x^(2^k) to x^(2^(k+1)). - Shift
eright by one to drop the bit you just used. - Return
result. Whennis 0 the loop never runs andresultis 1.
Dry run
Start with x = -2, n = -2147483648. The exponent is negative, so x becomes -0.5 and e becomes 2^31, whose binary form is a 1 followed by 31 zeros. Only the top bit is set. Initial state: result = 1, x = -0.5, e = 2^31.
| Iteration | Lowest bit of e | result | x after squaring | e after shift |
|---|---|---|---|---|
| 1 | 0 | 1 | 2^-2 | 2^30 |
| 2 | 0 | 1 | 2^-4 | 2^29 |
| 3 | 0 | 1 | 2^-8 | 2^28 |
| 4 | 0 | 1 | 2^-16 | 2^27 |
| 5 | 0 | 1 | 2^-32 | 2^26 |
| 6 | 0 | 1 | 2^-64 | 2^25 |
| 7 | 0 | 1 | 2^-128 | 2^24 |
| 8 | 0 | 1 | 2^-256 | 2^23 |
| 9 | 0 | 1 | 2^-512 | 2^22 |
| 10 | 0 | 1 | 2^-1024 | 2^21 |
| 11 | 0 | 1 | 0 (2^-2048 underflows) | 2^20 |
| 12 to 31 | 0 | 1 | 0 | down to 1 |
| 32 | 1 | 1 * 0 = 0 | 0 | 0 |
The loop ends because e is 0, and the function returns 0. For a smaller check, x = 2, n = 13 (binary 1101) multiplies in 2, skips 4, then multiplies in 16 and 256, giving 2 * 16 * 256 = 8192.
Complexity
| Time | O(log |n|) |
|---|---|
| Space | O(1) |
Let n be the exponent. Each iteration shifts e right by one, so the loop runs once per bit of |n|, which is at most 32 for a 32-bit input. Each iteration does at most two multiplications and one shift. The loop keeps only result, x and e, so space is constant.
PythonTested in our runner
from typing import List, Optional
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
x = 1.0 / x
n = -n
result = 1.0
while n > 0:
if n & 1: # this bit of the exponent is set
result *= x
x *= x # x becomes the next power of two power
n >>= 1
return result
JavaTested in our runner
import java.util.*;
class Solution {
public double myPow(double x, int n) {
long e = n; // widen first so -2^31 can be negated
if (e < 0) {
x = 1.0 / x;
e = -e;
}
double result = 1.0;
while (e > 0) {
if ((e & 1) == 1) {
result *= x;
}
x *= x;
e >>= 1;
}
return result;
}
}
C++Tested in our runner
class Solution {
public:
double myPow(double x, int n) {
long long e = n; // widen first so -2^31 can be negated
if (e < 0) {
x = 1.0 / x;
e = -e;
}
double result = 1.0;
while (e > 0) {
if (e & 1LL) {
result *= x;
}
x *= x;
e >>= 1;
}
return result;
}
};
JavaScriptTested in our runner
/**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function(x, n) {
if (n < 0) {
x = 1 / x;
n = -n;
}
let result = 1;
// Math.floor(n / 2) avoids the 32-bit limit of >>, since n can be 2^31
while (n > 0) {
if (n % 2 === 1) {
result *= x;
}
x *= x;
n = Math.floor(n / 2);
}
return result;
};
GoTested in our runner
func myPow(x float64, n int) float64 {
e := int64(n) // widen first so -2^31 can be negated
if e < 0 {
x = 1.0 / x
e = -e
}
result := 1.0
for e > 0 {
if e&1 == 1 {
result *= x
}
x *= x
e >>= 1
}
return result
}
C#Tested in our runner
public class Solution {
public double myPow(double x, int n) {
long e = n; // widen first so -2^31 can be negated
if (e < 0) {
x = 1.0 / x;
e = -e;
}
double result = 1.0;
while (e > 0) {
if ((e & 1) == 1) {
result *= x;
}
x *= x;
e >>= 1;
}
return result;
}
}
Common mistakes
- Writing
n = -non a 32-bitintin Java, C++ or C#. The value -2^31 has no positive counterpart, so it overflows. Copyninto alongorlong longbefore you negate. - Negating the exponent but leaving
xunchanged for negativen. That returns x^|n| instead of its reciprocal. Setx = 1.0 / xin the same branch. - Squaring
xin the wrong place or skipping the squaring. Withoutx *= xevery set bit multiplies the same power of the base. Square once per iteration, after the bit test. - Initialising
result = xinstead of1.0. This returnsxforn = 0and adds one extra factor otherwise. 1.0 is the multiplicative identity. - In the recursive version, writing
power(b, e / 2) * power(b, e / 2). That calls the function twice per level and brings the cost back to O(|n|). Store the half result in a variable and square it. - In JavaScript, using
n >> 1orn & 1on 2^31. Bitwise operators convert to a 32-bit signed value, so 2^31 turns negative and the loop breaks. Usen % 2andMath.floor(n / 2).
Edge cases
n = 0with any non-zerox, such asx = -7: return 1. The loop never runs.n = -2147483648with|x| > 1, such asx = -2: the answer underflows to 0. Your code must not overflow when negating.n = 2147483647withx = 1: the answer is 1. The loop finishes in 31 iterations.x = -1with a huge oddn: the answer is -1, and with an evennit is 1. Squaring keeps the magnitude at 1.n = 1orn = -1: returnxor1 / x. One iteration handles it.x = 0with positiven: return 0. The constraints rule outx = 0with negativen, so1 / xis safe.
Follow-ups interviewers ask
- Why does the loop work for any exponent, and how would you prove it?
- Use an invariant. At the start of each iteration, result * x^e equals the original base raised to the original exponent. If e is odd, moving one factor of x into result keeps the product the same. Squaring x and halving e keeps it the same too, because (x^2)^(e/2) = x^e for even e. When e hits 0, result alone equals the answer.
- Can you avoid the reciprocal and handle negative n differently?
- Yes. Compute x^|n| with the same loop, then return 1 / result at the end. The catch is overflow: with
x = 2, n = -2^31the positive power overflows to infinity before you invert it, and 1 / infinity is 0, which happens to be right. Inverting the base first avoids reasoning about that. Both work for the stated constraints. - How would you compute x^n modulo m for integers, and does the same code work?
- The loop is the same, with
result = result * x % mandx = x * x % m. Keep every intermediate value below m so the product fits in a 64-bit integer when m is up to about 3 * 10^9. This is modular exponentiation, and it is why the technique appears in cryptography and combinatorics problems. For a negative exponent you need a modular inverse instead of 1 / x.
Pow(x, n) FAQ
What is the time complexity of Pow(x, n)?
The optimal solution runs in O(log |n|) time, because the exponent halves every iteration and a 32-bit exponent has at most 32 bits. The brute force that multiplies n times is O(|n|), which is up to about 2 billion steps. Space is O(1) for the iterative loop and O(log |n|) for the recursive one.
Why use exponentiation by squaring for Pow(x, n)?
Squaring doubles the exponent in one multiplication, so you reach x^(2^k) in k steps. Any exponent is a sum of distinct powers of two, so you multiply in only the powers whose bit is set. That turns n multiplications into about log2(n).
How do I handle a negative exponent in LeetCode 50?
Replace x with 1 / x and the exponent with its absolute value, then run the normal loop. This works because x^(-n) = (1 / x)^n. Do the negation on a 64-bit integer so that n = -2^31 does not overflow.
Can Pow(x, n) be solved in O(1) extra space?
Yes. The iterative bit loop keeps only result, x and the exponent, so extra space is constant. The recursive version needs O(log |n|) stack space, about 32 frames at most.
What is the difference between the recursive and iterative solutions in Python?
Both do O(log |n|) multiplications. The recursive one is shallow, about 32 calls, so Python's recursion limit is not a concern here. The iterative one avoids the call overhead and the stack. Python integers never overflow, so the minimum exponent needs no special handling in Python.
Why does Pow(x, n) return 0 for x = -2 and n = -2147483648?
The true value is 1 / 2^2147483648, which is far below the smallest positive double, about 4.9 * 10^-324. The repeated squaring of the base -0.5 underflows to 0 after 11 squarings, and the result then multiplies by 0. That matches the expected output of 0.
Asked at
See which companies ask this — Pro
Related problems
- Bitwise AND of Numbers Range · same technique: Bitwise Operations - Power of Two/Four Check
- Minimum Array End · same technique: Bitwise Operations - Power of Two/Four Check
- Power of Two · same technique: Bitwise Operations - Power of Two/Four Check
- Power of Four · same technique: Bitwise Operations - Power of Two/Four Check
- Sum of Two Integers · same pattern: Bit Manipulation Patterns
- Parallel Courses · same pattern: Bit Manipulation Patterns
- Single Number II · same pattern: Bit Manipulation Patterns
- Single Number · same pattern: Bit Manipulation Patterns
- Missing Number · same pattern: Bit Manipulation Patterns
- Counting Bits · same pattern: Bit Manipulation Patterns