50. Pow(x, n)

121 阅读1分钟
50\. Pow(x, n)
Medium
1636
3162
Add to List
Share

Implement pow(

[x](http://www.cplusplus.com/reference/valarray/pow/)

[,

n

)](www.cplusplus.com/reference/v…), which calculates

x

raised to the power

n

(xn).

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
class Solution:
    def myPow(self, x: float, n: int) -> float:

        neg = True if n < 0 else False
        n = abs(n)

        def fastPow(x, n):
            if n == 0:
                return 1
            if n == 1:
                return x
            half = fastPow(x, n // 2)
            if n %2:
                return half * half * x
            else:
                return half * half

        p = fastPow(x, n)
        return 1.0 / p if neg else p