就是使用二分法不断缩减low和high的范围,注意在high - low <=1时候终止,然后从high开始检查是不是x的平方根就可以了,判断条件是,high^2<=x,代码如下:
class Solution {
public:
int mySqrt(int x) {
if(x==0 || x == 1)return x;
int low=0 ,high=x,mid;
while(1){
if(high - low <= 1 ) break;
mid = (low+high)/2;
if(pow(mid,2)>x){high = mid;}
else if(pow(mid,2)<x){low = mid;}
else {return mid;}
}
for (;pow(high,2)>x; high--){}
return high;
}
};
成绩如下: