-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.py
More file actions
32 lines (29 loc) · 767 Bytes
/
Solution.py
File metadata and controls
32 lines (29 loc) · 767 Bytes
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
class Solution:
def mySqrtV1(self, x: int) -> int:
return int(x ** 0.5)
# 使用二分法求解
def mySqrtV2(self, x: int) -> int:
if x <= 1:
return x
l = 0
r = x
while l < r:
mid = (l + r) // 2
if mid == l:
return mid
ret = mid ** 2
if ret == x:
return mid
elif ret > x:
r = mid
elif ret < x:
l = mid
return l
# The Babylonian square-root algorithm
def mySqrtV3(self, x: int) -> int:
if x <= 1:
return x
sqrt = int(x / 2)
while sqrt * sqrt > x:
sqrt = int((sqrt + x / sqrt) / 2)
return sqrt