Implement int sqrt(int x)
.
Compute and return the square root of x.
Subscribe to see which companies asked this question
提示是十一哦那个二分法,那么设置low = 0, high = x 进行二分查找,对于最后结果返回的low-1 还没想明白为什么...
代码:
public int mySqrt(int x) {
//二分搜索题
long low = 0;
long high = x;
while(low<=high){
long mid = low + (high-low)/2;
if(mid * mid == x){
return (int)mid;
}else if(mid * mid < x){
low = mid +1;
}else {
high = mid - 1;
}
}
return (int)low-1;
}