The method is in the discuss of the problem, it uses x/mid to compare with mid so that the situation mid*mid is very large is avoided.
class Solution {
public:
int mySqrt(int x) {
if(x<2)
return x;
int left=0,right=x,mid=(left+right)/2;
while(left<right)
{
if(x/mid>mid)
{
left=mid+1;
mid=(left+right)/2;
}
else if(x/mid<mid)
{
right=mid;
mid=(left+right)/2;
}
else
return mid;
}
return right-1;
}
};