实现函数 int mysqrt(int x).
计算并返回 x 的平方根(向下取整)
数据范围: ![](https://www.nowcoder.com/equation?tex=0%20%3C%3D%20x%20%3C%202%5E%7B31%7D-1)
要求:空间复杂度
,时间复杂度
# # # @param x int整型 # @return int整型 # class Solution: def mysqrt(self , x ): # write code here # 二分查找 # if x==1 or x==0: # return x # high = x # low = 0 # mid = (high+low)/2 # while abs(mid*mid - x) > 0.01: # if mid*mid>x: # high,mid = mid,(high+low)/2 # else: # low,mid = mid,(high+low)/2 # return int(mid) # 牛顿法 if x==1 or x==0: return x sqr = x/2 while abs(sqr*sqr - x)>0.01: sqr = (sqr+x/sqr)/2 return int(sqr)
# # @param x int整型 # @return int整型 #牛顿迭代法求平方根 class Solution: def mysqrt(self , x ): # write code here a=1.0 while abs(a*a-x)>1e-6: a=(a+x/a)/2 return a
# @param x int整型 # @return int整型 #不知道可不可以的直接法 class Solution: def mysqrt(self , x ): # write code here a=int(x**(1/2)) return a
class Solution: def mysqrt(self , x ): # write code here n = 1 while abs(n ** 2 - x) > 1e-5: n = n - (n ** 2 - x) / (2 * n) return int(n)
class Solution: def mysqrt(self , x ): # write code here if x==0: return 0 C,x0=x,x while True : xi=0.5*(x0+C/x0) if abs(x0-xi)<1e-7 : break x0=xi return int(x0)
class Solution: def equal(self,low,high,m): if low>=high: return low mid=(high-low)//2+low if mid**2==m: return mid elif mid**2<m: return self.equal(mid + 1, high, m) else: return self.equal(low, mid - 1, m) def mysqrt(self , x ): # write code here if x<=0: return 0 low=1 high=x a=self.equal(low,high,x) if a**2>x: a-=1 return a