11.3 Pow(x, n)
11.3.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 50
- Difficulty: Medium
- URL: https://leetcode.com/problems/powx-n/
- Tags: NeetCode 150
- Techniques: Divide and Conquer, Recursion, Math
11.3.5 Solution - Fast Exponentiation
11.3.5.1 Walkthrough
Use exponentiation by squaring: x^n = (x^{n/2})^2 * x^{n%2}. Handle negative exponents by inverting x and negating n. Base cases are n == 0 -> 1, n == 1 -> x.
11.3.5.3 Implementation Steps
- If
n == 0, return1. - If
n < 0, invertxand negaten. - Recursively compute
half = pow(x, n / 2). - Combine as
half * half * (n % 2 == 0 ? 1 : x).