【题目】

对非负数求平方根,不能调用系统自带库

 

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.

 

Example 1:

Input: x = 4
Output: 2

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.

 

 

【思路】

二分查找理解起来简单,但有很多易错点。

  • 右边界要不要-1,循环时left<=right还是left<right 可以看这篇讲的很清楚 https://www.cnblogs.com/kyoner/p/11080078.html
  • mid不能直接(L+R)/2,可能溢出,要写成 left+(right-left)/2 (JAVA和C++编程语言的bug,Python不会)
  • 以及注意mid*mid=x和mid=x/mid,两者有区别!!/是向下取整,想不通就测试下2147395599

 

 

【代码】

 

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

 

 posted on 2021-08-18 15:44  alau  阅读(136)  评论(0编辑  收藏  举报