Problem
Implement pow(x, n), which calculatesx raised to the power n (i.e., x<sup>n</sup>).
Examples
Constraints
- -100.0 < x < 100.0
- -2^31 <= n <= 2^31 - 1
nis an integer.- Either
xis not zero orn > 0. - -10^4 <= x^n <= 10^4
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 50 with 16 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 50 # by problem number
lcpy gen -s powx_n # by problem name
x raised to the power n (i.e., x<sup>n</sup>).
Input: x = 2.00000, n = 10
Output: 1024.00000
Input: x = 2.10000, n = 3
Output: 9.26100
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25
n is an integer.x is not zero or n > 0.class Solution:
# Time: O(log n)
# Space: O(log n)
def my_pow(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if n < 0:
return 1.0 / self.my_pow(x, -n)
if n % 2 == 0:
half = self.my_pow(x, n // 2)
return half * half
return x * self.my_pow(x, n - 1)
| Time | Space |
|---|---|
| O(log n) | O(log n) |