Leetcode 69.x 的平方根(Python3)

69.x 的平方根

实现 int sqrt(int x) 函数。

计算并返回 x 的平方根,其中 是非负整数。

由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

示例 1:

输入: 4
输出: 2

示例 2:

输入: 8
输出: 2
说明: 8 的平方根是 2.82842..., 
     由于返回类型是整数,小数部分将被舍去。

自己写的代码:

思想:二分查找

#sqrtx
class Solution:
    def mySqrt(self, x):
        if x <= 1:
            return x
        low = 1
        high = x
        while low <= high:
            mid = (low + high) // 2
            guess = mid ** 2
            if guess == x:
                return mid
            elif guess > x :
                high = mid - 1
            else:
                low = mid + 1
        return low - 1

大神的代码:

思想:牛顿迭代法,也是该题的思想

class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x <= 1:
            return x
        r = x
        while r > x / r:
            r = (r + x / r) // 2
        return int(r)

PS:这题import math.sqrt()都能通过,什么鬼

链接:

https://leetcode-cn.com/problems/sqrtx/

猜你喜欢

转载自blog.csdn.net/qq_38575545/article/details/84975498