Pow(x, n)
MedPrompt
Input: x = 2.00000, n = 10
Output: 1024.00000Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Constraints:
-100.0 < x < 100.0-231 <= n <= 231-1nis an integer.- Either
xis not zero orn > 0. -104 <= xn <= 104
Approaches
3 approaches with complexity analysis and trade-offs.
This approach simulates the basic definition of exponentiation by repeatedly multiplying the base x for n times. It's the most straightforward but least efficient method.
Algorithm
- Convert the integer
nto a longNto handle theInteger.MIN_VALUEcase. - If
Nis negative, updatexto1/xandNto-N. - Initialize a variable
ansto1.0. - Iterate from
0toN-1. - In each iteration, multiply
ansbyx. - After the loop, return
ans.
Walkthrough
The algorithm handles three main cases for the exponent n:
- Positive
n: We initialize a result to1.0and multiply it byxexactlyntimes in a loop. nis zero: By definition,x^0is1, so we return1.0.- Negative
n: We use the propertyx^-n = 1 / x^n. To avoid integer overflow whennisInteger.MIN_VALUE, we first convertnto along. Then, we can safely negate it. We calculate the power for the positive exponent-nand then take its reciprocal. A small optimization for the negative case is to compute(1/x)^-ninstead.
public class Solution { public double myPow(double x, int n) { long N = n; if (N < 0) { x = 1 / x; N = -N; } double ans = 1.0; for (long i = 0; i < N; i++) { ans = ans * x; } return ans; }}Complexity
Time
O(n)
Space
O(1)
Trade-offs
Pros
Very simple to understand and implement.
Works correctly for small values of
n.
Cons
Extremely inefficient for large values of
n.Will result in a 'Time Limit Exceeded' (TLE) error on most online judges due to the O(n) complexity.
Solutions
Solution
public class Solution { public double MyPow(double x, int n) { return n >= 0 ? qpow(x, n) : 1.0 / qpow(x, -(long) n); } private double qpow(double a, long n) { double ans = 1; for (; n > 0; n >>= 1) { if ((n & 1) == 1) { ans *= a; } a *= a; } return ans; }}Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.