> For the complete documentation index, see [llms.txt](https://nataliekung.gitbook.io/ladder_code/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nataliekung.gitbook.io/ladder_code/meta-2025/50.-pow-x-n.md).

# 50. Pow(x, n)

math

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>).

&#x20;

**Example 1:**

<pre><code><strong>Input: x = 2.00000, n = 10
</strong><strong>Output: 1024.00000
</strong></code></pre>

**Example 2:**

<pre><code><strong>Input: x = 2.10000, n = 3
</strong><strong>Output: 9.26100
</strong></code></pre>

**Example 3:**

<pre><code><strong>Input: x = 2.00000, n = -2
</strong><strong>Output: 0.25000
</strong><strong>Explanation: 2-2 = 1/22 = 1/4 = 0.25
</strong></code></pre>

&#x20;

**Constraints:**

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

分析

Instead 每次\*x, **把步子指数型提高**，每次迈x\*x的步子，同时n//=2。奇数时候直接\*x

```
class Solution:
    def myPow(self, x: float, n: int) -> float:
        #扩大底数x  x=>x2 同时缩小n=//2 这样等于每次指数型扩大步子。
        if n < 0:
            n = -n
            x = 1 / x
        
        res = 1
        while n > 0:
            if n%2 == 1:
                res *= x
                n -= 1
            x *= x
            n //= 2
        return res
        
        

```
