## leetcode 69. Sqrt(x)（python）

### 描述

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.

Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

Example 1:

``````Input: x = 4
Output: 2

Example 2:

``````Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.

Note:

``````0 <= x <= 2^31 - 1

### 解析

• 直接遍历 [0, x // 2 + 2] 范围内的每个整数 i
• 如果 i * i == x ，直接返回 i
• 如果 i * i > x ，直接返回 i-1

### 解答

``````class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
for i in range(0, x // 2 + 2):
if i * i == x:
return i
if i * i > x:
return i - 1

### 运行结果

``````Memory Limit Exceeded

### 解答

``````class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
l, r = 0, x
while l <= r:
mid = (l + r) // 2
if mid ** 2 <= x < (mid + 1) ** 2:
return mid
elif x < mid ** 2:
r = mid - 1
else:
l = mid + 1

### 运行结果

``````Runtime: 37 ms, faster than 37.53% of Python online submissions for Sqrt(x).
Memory Usage: 13.3 MB, less than 66.04% of Python online submissions for Sqrt(x).

### 解答

``````class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
return int(sqrt(x))

### 运行结果

``````Runtime: 25 ms, faster than 61.40% of Python online submissions for Sqrt(x).
Memory Usage: 13.3 MB, less than 66.04% of Python online submissions for Sqrt(x).