Implement int sqrt(int x)
.
Compute and return the square root of x.
这道题么,当然最简单的方法就是一行代码 return(int)Math.sqrt(x);
不过出于强迫症,还是用二分法又写了一遍代码。需要注意的地方是循环应该是while(left <= right) 而不是 while(left < right) 因为当left == right的时候可能也不是答案,偏大了,这时候right会-1,返回right即可。代码如下:
public int mySqrt(int x) {
int left =0;
int right = x/2+1;
long mid = 0; //the long type prevent the overflow of int
while(left <= right){
mid = (left + right)/2;
System.out.println(left+" "+ right+" "+mid);
if(mid * mid == x){ // if mid is int , here may be fault
return (int)mid;
}else if(mid * mid > x){
right = (int)mid-1;
}else{
left = (int)mid+1;
}
}
return right;
}