```
public class Solution {
public int MySqrt(int x) {
if(x<0)
return -1;
long left=0,right=x;
//unit test: 0,1,2,3,4
while(left<=right)
{
long mid=left+(right-left)/2;
if(mid*mid==(long)x)
return (int)mid;
if(mid*mid>(long)x)
right=mid-1;
else
left=mid+1;
}
return (int)right;
}
}
```