Implement int sqrt(int x)
.
Compute and return the square root of x.
二分查找方法,最后需要有收敛条件。
class Solution:
# @param x, an integer
# @return an integer
def sqrt(self, x):
if (x<0):
print("not in domain")
low=0
high=x
mid=(low+high)/2
while (mid*mid!=x):
if (mid*mid>x):
high=mid-1
else:
low=mid+1
last=mid
mid=(low+high)/2
if (abs(last-mid)==0): #此处收敛很重要,到最后会重复计算,如果不是完全平方数以至于超时。
break
return mid