这题也是利用二分查找来计算。
首先区间是[0,x]。通过x/2的平方判断应该区间左移还是区间右移,同时值得注意的是要记录mid的平方小于x的mid值,因为比如8的平方根是2,所以平方小于x的mid要记录。
class Solution {
public:
int mySqrt(int x) {
int left = 0, right = x ,ans = 0;
while(left <= right){
int mid = left + (right - left) / 2;
if((long long)mid * mid == x){
return mid;
}else if((long long)mid * mid > x){
right = mid -1;
}else{
ans = mid;
left = mid + 1;
}
}
return ans;
}
};
标签:平方,int,mid,ans,69,平方根,left From: https://www.cnblogs.com/llllmz/p/18399277