-
Notifications
You must be signed in to change notification settings - Fork 17
/
Sqrtx_069.py
47 lines (36 loc) · 945 Bytes
/
Sqrtx_069.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
'''
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated,
and only the integer part of the result is returned
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
'''
import math
class SolutionLibrary:
def mySqrt(self, x):
return int(math.sqrt(x))
class Solution:
# Binary Search
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0:
return 0
left = 1
right = x // 2 + 1
while left <= right:
mid = (right + left) // 2
if mid ** 2 <= x < (mid+1) ** 2:
return mid
if mid ** 2 > x:
right = mid - 1
else:
left = mid + 1