实现函数 int mysqrt(int x).
计算并返回 x 的平方根(向下取整)
数据范围:
要求:空间复杂度 ,时间复杂度
class Solution: def mysqrt(self , x: int) -> int: # write code here left=0 right=x while left<=right: root=(left+right)//2 if root*root<x: if (root+1)*(root+1)<x: left=root+1 elif (root+1)*(root+1)==x: return root+1 elif (root+1)*(root+1)>x: return root elif root*root>x: if (root-1)*(root-1)>x: right=root-1 elif (root-1)*(root-1)==x: return root-1 elif (root-1)*(root-1)<x: return root-1 elif root*root==x: return root
class Solution: def mysqrt(self , x: int) -> int: if x == 0: return 0 elif x == 1: return 1 else: i=0 while i*i <= x: i+=1 return(i-1)
class Solution: def mysqrt(self , x ): # write code here if x==0: return 0 if x==1: return 1 if x ==2: return 1 else: lower = 0 ans = 0 upper = x while True: mid = (upper - lower) // 2 + lower if mid * mid <= x: if (mid + 1) * (mid + 1) > x: ans = mid return ans else: lower = mid else: upper = midmark
class Solution: # 二分法 def mysqrt(self, x): if x < 2: return x i, j = 1, x // 2 last = 0 while i <= j: mid = i + (j - i) // 2 if x // mid < mid: j = mid - 1 elif x // mid > mid: i = mid + 1 last = mid else: return mid return last # 直接返回平方根,向下取整 def mysqrt2(self , x ): return int(x**0.5) # 奇数相加一定是平方数 def mysqrt3(self , x ): res = 0 begin = 1 while x >= 0: x -= begin res += 1 begin += 2 return res-1