classSolution: defmySqrt(self, x: int) -> int: if x == 0or x == 1: return x left, right = 1, x // 2 while left < right: mid = int((left + right + 1) >> 1) if mid * mid > x: right = mid - 1 else: left = mid return left
执行用时 : 52 ms 内存消耗 : 14 MB
解法二:牛顿法
1 2 3 4 5 6 7 8 9 10
classSolution: defmySqrt(self, x: int) -> int: if x == 0or x == 1: return x x0 = 0 x1 = x whileabs(x1 - x0) >= 1: x0 = x1 x1 = x1 / 2 + x / (2 * x1) returnint(x1)