powx

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
class (object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
>>> s = Solution()
>>> s.myPow(2.00000, 10)
1024.00000
>>> s.myPow(2.10000, 3)
9.26100
"""

if n == 0:
return 1
elif n > 0:
pass
else:
n = -n
x = 1 / x
if x == 1:
return 1
if x == -1:
return 1 if n % 2 == 0 else -1
return self.pow(x, n)

def pow(self, x, n):
# n is positive
if n == 0:
return 1
if n == 1:
return x
if n % 2 == 0:
return self.pow(x, n/2)**2
else:
return x*self.pow(x, n/2)**2


if __name__ == '__main__':
s = Solution()
print(s.myPow(0.000001, 2111121))