Implement int sqrt(int x).
Compute and return the square root of x.
依然二分法….这道题虽然简单,但是有一些细节需要注意,我是提交了好几遍才通过的!
参考代码:
class Solution
{
public:
int mySqrt(int x)
{
if (x < 2) return x;
int left = 1;
int right = x / 2;
int result;
while (left <= right)
{
int middle = (left + right) / 2;
if (x / middle < middle)
right = middle - 1;
else if (x / middle > middle)
{
left = middle + 1;
result = middle;
}
else return middle;
}
return result;
}
};