↓Skip to main content
  1. LeetCode/

LeetCode 50: Pow(x, n)

·2 mins· ·
LeetCode Medium Math Recursion
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-14

  • Submissions: Accepted (first try)

Approach
#

Fast exponentiation (Math Template 8): for even n, x^n = (x²)^(n/2), and odd n needs one more x; halving n each time takes O(log n) multiplications. For n < 0, switch to 1 / x and -n. The iterative version reads n in binary: each 1 bit multiplies the current x^(2^k) into the answer.

My Attempts
#

Passed on the first try with a recursive version: n < 0 returns 1 / myPow(x, -n), odd n gives x * myPow(x, n - 1), and even n gives myPow(x * x, n // 2).

Solution
#

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

Complexity
#

Time O(log n), space O(1).

Mistakes to Avoid
#

  • Multiplying one x at a time is O(n) and times out for n near 2^31.
  • Negative exponents take the reciprocal.
  • n = 0 gives 1.

Interview Explanation
#

I use fast exponentiation over the bits of n: multiply the current x into the answer for each 1 bit, square x and shift n each step; for negative n I switch to 1 / x and -n. Time O(log n).

Related

LeetCode 2: Add Two Numbers
·2 mins
LeetCode Medium Linked-List Math Recursion
LeetCode 2 note: digits are stored in reverse, so add from the head digit by digit with a carry, looping until both lists end and no carry remains
LeetCode 264: Ugly Number II
·2 mins
LeetCode Medium Hash-Table Math Dynamic-Programming Heap-Priority-Queue
LeetCode 264 note: three pointers mark the next ugly numbers to multiply by 2, 3 and 5; take the minimum each time and advance every pointer that produced it
LeetCode 227: Basic Calculator II
·2 mins
LeetCode Medium Math String Stack
LeetCode 227 note: read whole numbers, and at each operator apply the previous one: + and - push the number (negated for -), * and / combine with the top
LeetCode 189: Rotate Array
·2 mins
LeetCode Medium Array Math Two-Pointers
LeetCode 189 note: take k %= n, then reverse three times: the whole array, the first k, and the last n - k, with O(1) extra space
LeetCode 204: Count Primes
·2 mins
LeetCode Medium Array Math Enumeration Number-Theory
LeetCode 204 note: the sieve of Eratosthenes, crossing out multiples of each prime p starting at p², with the outer loop only up to √n
LeetCode 48: Rotate Image
·2 mins
LeetCode Medium Array Math Matrix
LeetCode 48 note: rotating 90 degrees clockwise is a transpose followed by reversing each row, both in place