> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Pow(x, n) Python Solution with Tests

> Tested Python solution for LeetCode 50 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 50, Medium. Topics: Math, Recursion. [View on LeetCode](https://leetcode.com/problems/powx-n/description/).

Generate this problem as a practice environment: tested reference solution, 16 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 50   # by problem number
lcpy gen -s powx_n   # by problem name
```

## Problem

Implement [pow(x, n)](http://www.cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., x\<sup>n\</sup>).

### Examples

```
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
```

### Constraints

* -100.0 \< x \< 100.0
* -2^31 \<= n \<= 2^31 - 1
* `n` is an integer.
* Either `x` is not zero or `n > 0`.
* -10^4 \<= x^n \<= 10^4

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/powx_n/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/powx_n/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
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)
```

## Complexity

| Time     | Space    |
| -------- | -------- |
| O(log n) | O(log n) |

## Tags

[Grind](/catalog/grind), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
