Leetcode 50: Pow(x, n)

grid47
grid47
Exploring patterns and algorithms
Nov 2, 2024 4 min read

A soft, glowing beam expanding and contracting in gentle rhythmic pulses.
Solution to LeetCode 50: Pow(x, n) Problem

You are given a number x and an integer n. Your task is to compute x raised to the power n (i.e., x^n). Handle cases where the exponent is negative by returning the reciprocal of the result.
Problem
Approach
Steps
Complexity
Input: The input consists of a number `x` (float) and an integer `n` (int).
Example: ["x = 3.00000, n = 4"]
Constraints:
• -100.0 < x < 100.0
• -231 <= n <= 231-1
• n is an integer.
• Either x is not zero or n > 0.
Output: The output should be a float value, which is `x` raised to the power `n`.
Example: ["81.00000"]
Constraints:
• The result must be computed within the constraints of the problem.
Goal: The goal is to calculate `x^n` efficiently, especially for large `n` values.
Steps:
• 1. Check if the exponent `n` is zero. If so, return 1.
• 2. If `n` is negative, compute the power of the reciprocal of `x` raised to the positive exponent.
• 3. Use fast exponentiation (divide-and-conquer) for optimal computation, where the power is halved for each recursive step.
Goal: The input consists of a floating point number `x` and an integer `n`.
Steps:
• x is a float in the range (-100.0, 100.0).
• n is an integer between -231 and 231-1.
• x will not be zero when n <= 0.
Assumptions:
• The function should handle both positive and negative exponents correctly.
• The input constraints guarantee that no invalid values (such as x = 0 when n <= 0) will be provided.
Input: ["x = 3.00000, n = 4"]
Explanation: In this example, `3^4` is calculated, resulting in `81.00000`.

Input: ["x = 2.50000, n = -2"]
Explanation: Here, `2.5^-2` is computed as the reciprocal of `2.5^2`, resulting in `0.16000`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus