Implement int sqrt(int x)
.
Compute and return the square root of x.
Subscribe to see which companies asked this question
二分法,最后再加一个处理
这么简单的题目竟然才做。。sigh
class Solution(object):
def mySqrt(self, x):
start = 1
end = x
while start < end:
#print start,mid,end
mid = (start + end) / 2
res = mid ** 2
if res > x:
end = mid - 1
elif res == x:
return mid
else:
start = mid + 1
if start ** 2 > x:
start -= 1
return start