-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path050.py
41 lines (36 loc) · 954 Bytes
/
050.py
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
36
37
38
39
40
41
#==================================================
#==> Title: powx-n
#==> Author: Zhang zhen
#==> Email: hustmatnoble.gmail.com
#==> GitHub: https://github.com/MatNoble
#==> Date: 1/11/2021
#==================================================
"""
https://leetcode-cn.com/problems/powx-n/
"""
class Solution:
def myPow(self, x: float, n: int) -> float:
if x == 0.0: return 0.0
res = 1.0
if n < 0: x, n = 1.0 / x, -n
while n:
if n & 1: res *= x
x *= x
n >>= 1
return res
def myPowR(self, x: float, n: int) -> float:
if x == 0.0: return 0.0
if n == 0: return 1.0
res = self.myPowR(abs(x), abs(n) // 2)
res *= res
if abs(n) % 2: res *= x
return 1/res if n<0 else res
x = 0
x = -3
x = 3
n = 1
n = 5
n = -5
mat = Solution()
print(mat.myPow(x, n))
print(mat.myPowR(x, n))