0
点赞
收藏
分享

微信扫一扫

LeetCode知识点总结 - 69

小编 2022-01-10 阅读 23

LeetCode 69. Sqrt(x)

考点难度
MathEasy
题目

Given a non-negative integer x, compute and return the square root of x.

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

思路

用binary search的方法,先设定left是1,right是x/2,再比较midx/mid,根据结果缩小范围。

答案
public int mySqrt(int x) {
        if (x == 0)
            return 0;
        int left = 1, right = x/2;
        while (true) {
            int mid = left + (right - left)/2;
            if (mid > x/mid) {
                right = mid - 1;
            } else {
                if (mid + 1 > x/(mid + 1))
                    return mid;
                left = mid + 1;
            }
        }
}
举报

相关推荐

0 条评论