Implement int sqrt(int x)
.
Compute and return the square root of x.
class Solution {
public:
int mySqrt(int x) {
if(x<=0) return 0;
int begin=1, end=x, mid=0, res=0, tmp=0;
while(begin<=end)
{
mid=begin+(end-begin)/2;
tmp=x/mid;
if(tmp>mid)
{
res=mid;
begin = mid;
}
else if(tmp<mid)
{
end = end-1;
}
else if(tmp==mid)
{
res=mid;
break;
}
}
return res;
}
};