就是使用二分法不斷縮減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;
}
};
成績如下: