# x 的平方根

<p>实现&nbsp;<code>int sqrt(int x)</code>&nbsp;函数。</p>
<p>计算并返回&nbsp;<em>x</em>&nbsp;的平方根，其中&nbsp;<em>x </em>是非负整数。</p>
<p>由于返回类型是整数，结果只保留整数的部分，小数部分将被舍去。</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> 4<strong><br />输出:</strong> 2</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> 8<strong><br />输出:</strong> 2<strong><br />说明:</strong> 8 的平方根是 2.82842..., 由于返回类型是整数，小数部分将被舍去。</pre>
<p>以下错误的选项是？</p>

## aop

### before

```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after

```cpp
int main()
{
    Solution sol;

    int x = 8;
    int res;
    res = sol.mySqrt(x);
    cout << res;
    return 0;
}
```

## 答案

```cpp
class Solution
{
public:
    int mySqrt(int x)
    {
        long long i = 0;
        long long res;
        long long nextRes;
        for (i = 1; i <= x / 2 + 1; i++)
        {
            res = i * i;
            nextRes = (i + 1) * (i + 1);
            if (res < x && nextRes > x)
                break;
        }
        return i;
    }
};
```

## 选项


### A

```cpp
class Solution
{
public:
    int mySqrt(int x)
    {
        if (x == 0)
            return 0;
        double last = 0;
        double res = 1;
        while (res != last)
        {
            last = res;
            res = (res + x / res) / 2;
        }
        return int(res);
    }
};
```

### B

```cpp
class Solution
{
public:
    int mySqrt(int x)
    {

        long long i = 0;
        long long j = x / 2 + 1;
        while (i <= j)
        {
            long long mid = (i + j) / 2;
            long long res = mid * mid;
            if (res == x)
                return mid;
            else if (res < x)
                i = mid + 1;
            else
                j = mid - 1;
        }
        return j;
    }
};
```

### C

```cpp
class Solution
{
public:
    int mySqrt(int x)
    {
        return sqrt(x);
    }
};
```
