二分法求x的平方根(C语言)
关键的问题在于确定最终返回的数的选择。
int mySqrt(int x){
int low=0;
int height=x;
int mid=0,s;
if(x==0)
{
return 0;
}
else if(x==1)
{
return 1;
}
while(low<=height)
{
mid=(height+low)/2;
s=x/mid;
if(mid==s)
{
return mid;
}
else if(mid<s)
{
low=mid+1;
}
else{
height=mid-1;
}
}
return height;
}