forked from y-ncao/Python-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPowx-n.py
30 lines (29 loc) · 907 Bytes
/
Powx-n.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
"""
Implement pow(x, n).
"""
class Solution:
# @param x, a float
# @param n, a integer
# @return a float
def pow(self, x, n):
if x == 0 or x == 1:
return x
elif x < 0 and n % 2 == 0:
return self.pow(-x, n)
elif x < 0 and n % 2 ==1:
return self.pow(-x, n) * (-1)
elif n < 0:
return 1.0 / self.pow(x, -n)
elif n == 0:
return 1.0
# Notice here:
# 1. Must checks: n < 0 and n == 0
# 2. No need to check x, but if x == 0 or 1 will reduce calculation
# 3. Below the code, need to store half, if doing self.pow all the time, it's O(n) but not O(logn)
half = self.pow(x, n/2)
if n % 2 == 0:
return half * half
else:
return half * half * x
# Note to use the half var to make the code clean
# O(logn) complexity