SDE & MLE Prep

50. Pow(x, n)

Problem

Compute xⁿ for a float x and an integer n, which may be negative.

Example: x = 2.0, n = 10 → 1024.0; x = 2.0, n = -2 → 0.25

Constraints: n is a 32-bit integer; aim for O(log n) multiplications.

Binary exponentiation: x^n = (x²)^(n/2) (· x if n is odd). Negative n → 1 / x^(−n) (use a long for −Integer.MIN_VALUE).

x^13, 13 = 1101b
bit 1: res *= x       x -> x^2
bit 0:                x^2 -> x^4
bit 1: res *= x^4     x^4 -> x^8
bit 1: res *= x^8     => x^(1+4+8) = x^13

Complexity: O(log n).

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n < 0:
            x, n = 1 / x, -n
        res = 1.0
        while n:
            if n & 1:
                res *= x
            x *= x
            n >>= 1
        return res