-
Notifications
You must be signed in to change notification settings - Fork 17
/
powx-n.py
65 lines (47 loc) · 1.49 KB
/
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Solution:
def myPow(self, x, n):
def power(x, n):
if n == 1:
return x
elif n == 0:
return 1
else:
return power(x * x, n // 2) * power(x, n % 2)
if n >= 0:
return power(x, n)
elif n < 0:
return 1 / power(x, -n)
def myPowIterative(self, x: float, n: int) -> float:
result = 1.0
num = x
pow = 1
# Using the property that each number can
# be represented as a sum of powers of 2
while pow <= abs(n):
result *= num if abs(n) & pow else 1
num *= num
pow <<= 1
return result if n >= 0 else 1 / result
class TestSolution:
def setup(self):
self.sol = Solution()
def test_zero1(self):
assert self.sol.myPow(0, 0) == 1
def test_zero2(self):
assert self.sol.myPow(0, 1) == 0
def test_zero3(self):
assert self.sol.myPow(0, 2) == 0
def test_one1(self):
assert self.sol.myPow(1, 0) == 1
def test_one2(self):
assert self.sol.myPow(1, 1) == 1
def test_one3(self):
assert self.sol.myPow(1, 4) == 1
def test_custom1(self):
assert self.sol.myPow(2, 10) == 1024
def test_custom2(self):
assert self.sol.myPow(2.1, 3) == 9.261000000000001
def test_custom3(self):
assert self.sol.myPow(2, -2) == 0.25
def test_custom4(self):
assert self.sol.myPow(2, 11) == 2048