方法1:数学公式
class Solution {
public:
int mySqrt(int x) {
if(!x){
return 0;
}
int res = exp(0.5 * log(x));
if((long long )(res + 1) * (res + 1) <= x){ //精度不够
return res + 1;
}
return res;
}
};
方法2:二分查找
class Solution {
public:
int mySqrt(int x) {
int l = 0, r = x;
int res = -1;
while(l <= r){
int mid = l + (r - l) / 2;
if((long long) mid * mid <= x){
res = mid;
l = mid + 1;
}else{
r = mid - 1;
}
}
return res;
}
};