8000 50 · chaor/LeetCode_Python_Accepted@a13eb70 · GitHub
[go: up one dir, main page]

Skip to content

Commit a13eb70

Browse files
committed
50
1 parent 339f84b commit a13eb70

File tree

1 file changed

+13
-13
lines changed

1 file changed

+13
-13
lines changed

50_Pow_x_n.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
# 2015-09-07 Runtime: 60 ms
2-
class Solution:
3-
# @param {float} x
4-
# @param {integer} n
5-
# @return {float}
1+
# 2016-03-15 300 tests, 40 ms
2+
class Solution(object):
63
def myPow(self, x, n):
7-
# thanks to https://leetcode.com/discuss/9459/o-logn-solution-in-java
8-
if n < 0:
9-
x, n = 1.0 / x, -n
10-
res, f = 1, x
11-
while n > 0:
12-
if n % 2: res *= f
13-
f = f * f
4+
"""
5+
:type x: float
6+
:type n: int
7+
:rtype: float
8+
"""
9+
if n < 0: x, n = 1.0 / x, -n
10+
result, weight = 1, x
11+
while n: # consider binary
12+
if n & 1: result *= weight
13+
weight **= 2 # square
1414
n >>= 1
15-
return res
15+
return result

0 commit comments

Comments
 (0)
0