sqrt(x)
Use long instead of int to calculate.
code
class Solution {
public:
int mySqrt(int x) {
if(x <= 0)
{
return 0;
}
long s = 1;
long e = x;
while(s+1 < e)
{
long mid = s+(e-s)/2;
if(mid*mid == x)
{
return mid;
}
else if(mid * mid < x)
{
s = mid;
}
else
{
e = mid;
}
}
if(e * e < x)
{
return e;
}
else
{
return s;
}
}
};