题目:
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
示例 1:
输入: 4
输出: 2
示例 2:
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
Python代码1:
class Solution:
def mySqrt(self, x):
return int(math.sqrt(x))
python代码2:
class Solution:
def mySqrt(self, x):
if x == 0:
return 0
i = 1; j = x // 2 + 1
while( i <= j ):
center = ( i + j ) // 2
if center ** 2 == x:
return center
elif center ** 2 > x:
j = center - 1
else:
i = center + 1
return j
心得:python大法好!
本文介绍了两种实现整数平方根函数的方法。一种是利用Python内置的math库直接计算平方根并取整;另一种则是使用二分查找算法来精确找到满足条件的最大整数。这两种方法都能有效地解决该问题。
&spm=1001.2101.3001.5002&articleId=80357222&d=1&t=3&u=492febfc568c42cebaeeb6ff4441fba5)
308

被折叠的 条评论
为什么被折叠?



