Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
代码:
int mySqrt(int x) {
if(x <= 0)
return 0;
int left = 1;
int right = x;
int ans;
while (left <= right)
{
int mid = left + (right - left) / 2;
if(mid <= x / mid)
{
left = mid + 1;
ans = mid;
}
else
right = mid - 1;
}
return ans;
}
原题地址:
https://leetcode.com/problems/sqrtx/