solution.md 2.0 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9
# 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>
F
fix bug  
feilong 已提交
10

每日一练社区's avatar
每日一练社区 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
## 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);
    }
};
```