#50

Pow(x, n)

Medium Fast exponentiation

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Compute x raised to an integer power n, where n can be negative and as large as 2^31 in size.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: x to the power n where n can be about ±2 billion.

Why this works: x^13 = x^8 · x^4 · x^1 (13 is 1101 in binary). Squaring x each step gives x, x², x⁴, x⁸; multiply in the ones whose bit is set. That's about 31 steps instead of 2 billion.

Example: x = 2, n = 10 (binary 1010)

bit 0 = 0: base 2 → 4bit 1 = 1: result 4,   base 16bit 2 = 0: base 256bit 3 = 1: result 4·256 = 1024

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Writing n = -n with an int when n == Integer.MIN_VALUE — it stays negative.