69. x 的平方根
题目描述
解题思路
二分法查找
代码实现
class Solution:
def mySqrt(self, x: int) -> int:
low, high = 0, x
while low <= high:
mid = low + (high - low) // 2
mid2 = mid ** 2
# 向下取整,第一个小于等于就是答案
if mid2 <= x and (mid + 1) ** 2 > x:
return mid
elif mid2 > x:
high = mid - 1
else:
low = mid + 1
def mySqrt3(self, x: int) -> int:
""" 牛顿法 """
cur = 1
while True:
pre = cur
cur = (cur + x / cur) / 2
if abs(cur - pre) < 1e-6:
return int(cur)