求平方根,这一题discussion中有一道很好的二分查找的办法,代码实现如下:
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0:
return 0
left = 1
right = pow(2, 31) - 1
while True:
mid = (left + right) / 2
if mid > x / mid:
right = mid - 1
else:
if (mid + 1) > x / (mid + 1):
return mid
else:
left = mid + 1