Skip to content

[LeetCode] 50. Pow(x, n)

Published: at 05:52 AM (2 min read)

Table of Contents

Open Table of Contents

Description

Implement the function pow(x, n), which calculates x raised to the power n (i.e., xnx^n).

Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000

Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100

Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 22=1/(22)=0.252^{-2} = 1 / (2^2) = 0.25

Approach

We can use Exponentiation by Squaring to compute xnx^n efficiently. Instead of multiplying xx by itself nn times, we recursively break down the problem:

This recursive approach reduces the number of multiplications and handles both positive and negative exponents. By halving the exponent at each step, the algorithm achieves logarithmic time complexity.

Solution

/**
 * @param {number} x
 * @param {number} n
 * @return {number}
 */
var myPow = function (x, n) {
  // Base case: any number to the power 0 is 1
  if (n === 0) return 1;

  // Base case: power of 1 returns the base itself
  if (n === 1) return x;

  // Base case: power of -1 returns the reciprocal of the base
  if (n === -1) return 1 / x;

  const currentProduct = n % 2 ? x : 1;

  // Recursive call: square the base and halve the exponent (floor division)
  // Multiply by currentProduct if n is odd
  return currentProduct * myPow(x * x, Math.floor(n / 2)) || 0;
};

Complexity Analysis

Time Complexity

The time complexity is O(logn)O(\log |n|), because each recursive (or iterative) step halves the exponent, resulting in logarithmic growth with respect to n|n|.

Space Complexity

The space complexity is O(logn)O(\log |n|) for the recursive approach, due to the call stack depth. If implemented iteratively, the space complexity is O(1)O(1).


Previous Post
[Ruby] Fix rugged gem install error: CMake is required
Next Post
[Heroku] FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory