```
int mySqrt(int x) {
int mid;
int l = 1;
int r = x;
if(x==0) return 0;
while(1)
{
mid = l + (r-l)/2;
if(mid > x/mid)
{
r = mid - 1;
}
else
{
if(mid + 1 > x/ (mid+1)) return mid;
l = mid + 1;
}
}
}
```