思路:
用二分查找,端点值从0和x开始,当两端点数相邻了停止循环。
若停止循环了,则返回左端点——较小者。
1 class Solution(object): 2 def mySqrt(self, x): 3 """ 4 :type x: int 5 :rtype: int 6 """ 7 if x <= 1: 8 return x 9 low, high = 0, x 10 # 二分查找,当端点相邻了停止循环 11 while high > low + 1: 12 mid = int((high + low) / 2) 13 if x / mid > mid: 14 low = mid 15 elif x / mid < mid: 16 high = mid 17 else: 18 return mid 19 return low 20 21 22 if __name__ == '__main__': 23 solution = Solution() 24 print(solution.mySqrt(8))