描述
实现 int sqrt(int x)
函数,计算并返回 x 的平方根。
您在真实的面试中是否遇到过这个题? 是
样例
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(10) = 3
挑战
O(log(x))
所有要求时间复杂度O(log(x))的基本都是二分查找:
class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
# write your code here
if x==0:return 0
if x==1 or x==2 or x==3 or x==4:return 1
low,high=0,x//2
while low<high:
mid=(low+high)//2
if mid*mid<=x and (mid+1)*(mid+1)>x:
return mid
elif mid*mid<x:
low=mid
else:
high=mid
return -1
s = Solution()
print(s.sqrt(6))