令人头疼的二分法,还是无法信手拈来
看看我第一次的错误示范
class Solution {
public:
int mySqrt(int x) {
int low=0,high=x,medium;
int temp,result;
while(low<=high)
{
medium=(low+high)/2;
temp=medium*medium;
if(temp==x)
return medium;
else if (temp<x)
low=medium+1;
else
high=medium-1;
}
return low*low<=x?low:low-1;
}
};
最终结果这样:
class Solution {
public:
int mySqrt(int x) {
long low=0,high=x,medium;
long temp;
while(low<=high)
{
medium=(low+high)/2;
temp=medium*medium;
if(temp==x)
return medium;
else if (temp<x)
low=medium+1;
else
high=medium-1;
}
return low*low<=x?low:low-1;
}
};