https://leetcode-cn.com/problems/sqrtx
二分法,找到一个数mid,当它的平方小于等于x,它加1的平方大于x,则这个数就是要找的数:
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
# 二分法
left, right = 0, x
while left <= right:
mid = (left+right) // 2
if mid*mid <= x:
if (mid+1)*(mid+1) > x:
return mid
else:
left = mid + 1
else:
right = mid - 1