Skip to content

Commit 40f7aa7

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 18.1 MB (5.03%)
1 parent 458da18 commit 40f7aa7

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

0050-powx-n/solution.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,29 @@
1+
# Approach 2: Binary Exponentiation (Iterative)
2+
3+
# Time: O(log n)
4+
# Space: O(1)
5+
16
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+
227
def myPow(self, x: float, n: int) -> float:
3-
return x ** n
28+
return self.binaryExp(x, n)
429

0 commit comments

Comments
 (0)