Leetcode:69. Sqrt(x)
Description
Implement int sqrt(int x).
Compute and return the square root of x.
思路
- 二分查找
代码
class Solution {
public:
int mySqrt(int x) {
if (x < 0) return INT_MIN;
if (x <= 1) return x;
int low = 1, high = x, mid = 0, res = 1;
while(low <= high){
mid = low + (high - low) / 2;
if(mid <= x / mid){
low = mid + 1;
res = mid;
}
else high = mid - 1;
}
return res;
}
};