x 的平方根
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去
方法1:二分法
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0:
return 0
if x == 1:
return 1
i, j = 1, x-1
while i <= j:
mid = (i + j) // 2
if mid * mid > x:
j = mid - 1
else:
i = mid + 1
return j
方法2:牛顿迭代法,参考
if x == 0:
return 0
if x == 1:
return 1
n = x
while True:
n = (n + x / n) / 2
if abs(n ** 2 - x) <= 0.01:
return float(format(x0, ".2f"))