We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 458da18 commit 40f7aa7Copy full SHA for 40f7aa7
0050-powx-n/solution.py
@@ -1,4 +1,29 @@
1
+# Approach 2: Binary Exponentiation (Iterative)
2
+
3
+# Time: O(log n)
4
+# Space: O(1)
5
6
class Solution:
7
+ def binaryExp(self, x: float, n: int) -> float:
8
+ if n == 0:
9
+ return 1
10
11
+ if n < 0:
12
+ n = -1 * n
13
+ x = 1.0 / x
14
15
+ result = 1
16
+ while n != 0:
17
+ if n % 2 == 1:
18
+ result *= x
19
+ n -= 1
20
21
+ x *= x
22
+ n //= 2
23
24
+ return result
25
26
27
def myPow(self, x: float, n: int) -> float:
- return x ** n
28
+ return self.binaryExp(x, n)
29
0 commit comments