# 二分搜索-求根

java

```java
/**
 * 69. x 的平方根
 * 实现 int sqrt(int x) 函数。
 *
 * 计算并返回 x 的平方根，其中 x 是非负整数。
 *
 * 由于返回类型是整数，结果只保留整数的部分，小数部分将被舍去。
 *
 * 示例 1:
 * 输入: 4
 * 输出: 2
 *
 * 示例 2:
 * 输入: 8
 * 输出: 2
 * 说明: 8 的平方根是 2.82842...,
 * 由于返回类型是整数，小数部分将被舍去。
 */
public class Solution69 {

    /**
     * 调用系统库
     * @param x
     * @return
     */
    public int mySqrt(int x) {
        return (int)Math.sqrt(x);
    }

    /**
     * 这个方法我还不太理解，备注
     * @param x
     * @return
     */
    public int mySqrt2(int x) {
        if(x<=1) return x;
        long m=x;
        while(m>x/m){
            m=(m+x/m)/2;
        }
        return (int)m;
    }

    public static void main(String[] args) {
        int x = 8;
        int r = new Solution69().mySqrt(x);
        int r2=new Solution69().mySqrt2(x);
        System.out.println("Method1:"+r);
        System.out.println("Method2:"+r2);
    }
}
```

python

```python
class Solution:
    # @param {integer} x
    # @return {integer}
    def mySqrt(self, x):
        if x < 0:
            return -1
        elif x == 0:
            return 0

        start, end = 1, x
        while start + 1 < end:
            mid = start + (end - start) / 2
            if mid ** 2 == x:
                return mid
            # mid此时过大，那真实值在mid左边，所以end=mid逼近
            elif mid ** 2 > x:
                end = mid
            else:  # mid此时小于目标，那么真实在右边，所以start逼近
                start = mid
        return start


s = Solution()
print(s.mySqrt(9))
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/shua-ti/sou-suo-cha-zhao-lei/28-x-de-ping-fang-gen.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
