150NeetCode 150

141.Pow(x, n)

MediumMath & Geometry · 6/8

Problem

Implement pow(x, n), which computes x raised to the integer power n (that is, x^n).

n may be negative (meaning 1 / x^|n|) and can be as small as -2^31. Do not use Math.pow.

Examples

Input:  x = 2.00000, n = 10
Output: 1024.00000
Input:  x = 2.10000, n = 3
Output: 9.26100
Input:  x = 2.00000, n = -2
Output: 0.25000
Explanation: 2^-2 = 1 / 2^2 = 1/4 = 0.25.

Constraints

  • -100.0 < x < 100.0
  • -2^31 <= n <= 2^31 - 1
  • n is an integer.
  • Either x is not zero or n > 0.
  • -10^4 <= x^n <= 10^4

💡 Key Insight

Exponentiation by squaring: x^n = (x^(n/2))² when n is even and x · (x^(n/2))² when odd. Each step halves the exponent, so only O(log n) multiplications are needed instead of n. Handle a negative exponent by computing with 1/x and |n| — but store |n| in a long, because -(-2^31) overflows an int.

Brute Force (Repeated Multiplication)

TimeO(|n|)SpaceO(1).

Intuition

Multiply x by itself |n| times, then invert if n was negative. Correct, but n can be about two billion, which is far too slow (LeetCode times out).

Algorithm

  1. N = |n| as a long; if n < 0, set x = 1 / x.
  2. result = 1; repeat N times: result *= x.
  3. Return result.

Visualization

x = 2, n = 10
result: 1 → 2 → 4 → 8 → 16 → 32 → 64 → 128 → 256 → 512 → 1024   (10 multiplications)

Code

java
class Solution {
    public double myPow(double x, int n) {
        long N = n;            // long: -(-2^31) does not fit in an int
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
        double result = 1.0;
        for (long i = 0; i < N; i++) {
            result *= x;       // one multiplication per unit of exponent
        }
        return result;
    }
}

Complexity

  • Time: O(|n|) — up to about 2 · 10^9 multiplications; too slow.
  • Space: O(1).

Complexity Comparison

Approach Time Space
Repeated Multiplication O(n) O(1)
Recursive Fast Power O(log n) O(log n)
Iterative Binary Exponentiation O(log n) O(1)

Common Pitfalls

  • Negating n as an int — -Integer.MIN_VALUE is still Integer.MIN_VALUE, so the exponent stays negative. Use a long.
  • Calling fastPow(x, n / 2) twice instead of storing it in half — that is back to O(n) time.
  • Forgetting the odd case (half * half * x).
  • Inverting the final result instead of x is fine too, but don't do both.