50 Powx N
50 Powx N
Pow(x, n) 
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Example 1:
1
2
3
4
**Input:** x = 2.00000, n = 10
**Output:** 1024.00000
Example 2:
1
2
3
4
**Input:** x = 2.10000, n = 3
**Output:** 9.26100
Example 3:
1
2
3
4
5
**Input:** x = 2.00000, n = -2
**Output:** 0.25000
**Explanation:** 2-2 = 1/22 = 1/4 = 0.25
Constraints:
1
2
3
4
5
-100.0 < x < 100.0
-231 <= n <= 231-1
n is an integer.
Either x is not zero or n > 0.
-104 <= xn <= 104
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution:
def __init__(self):
self.dt = {}
def myPow(self, x: float, n: int) -> float:
multiplier = 1
if n < 0:
return 1/self.calc(x, -n)
return self.calc(x, n)
def calc(self, x: float, n : int) -> int:
if (str(x) + "$" + str(n)) in self.dt:
return self.dt[str(x) + "$" + str(n)]
if n <= 0:
return 1
if n == 1:
return x
result = 0
if n % 2 == 0:
result = self.calc(x, n/2) * self.calc(x, n/2)
else:
result = self.calc(x, (n+1)/2) * self.calc(x, (n-1)/2)
self.dt[str(x) + "$" + str(n)] = result
return result
This post is licensed under CC BY 4.0 by the author.