[LeetCode] 69. x 的平方根

题目链接 : https://leetcode-cn.com/problems/sqrtx/

题目描述:

实现 int sqrt(int x) 函数。

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

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

示例:

示例 1:

输入: 4
输出: 2

示例 2:

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

思路:

思路一:库函数

 def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        return int(math.sqrt(x))

思路二: 二分法

思路三: 牛顿法.

代码:

思路二:

class Solution:
    def mySqrt(self, x: int) -> int:
        left = 0
        right = math.ceil(x / 2)
        res = 0
        while left <= right:
            mid = left + (right - left) // 2
            tmp = mid * mid
            if tmp  ==  x:
                return mid
            elif tmp < x:
                left = mid + 1
            else:
                right = mid - 1
        return right

java

class Solution {
    public int mySqrt(int x) {
        int left = 1;
        int right = (x / 2) + 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (mid == x / mid) return mid;
            else if (mid < x / mid) left = mid + 1;
            else right = mid - 1;
        }
        return right;   
    }
}

思路三:

class Solution:
    def mySqrt(self, x: int) -> int:
        r = x
        while r * r > x:
            r = (r + x // r) // 2
        return r

java

class Solution {
    public int mySqrt(int x) {
        long r = x;
        while (r * r > x) r = (r + x / r) / 2;
        return (int) r;
    }
}
原文地址:https://www.cnblogs.com/powercai/p/10938404.html