public class Test {
public static void main(String[] args) {
System.out.println(new Test().sqrt(13));
}
int sqrt(int x ){
int left = 1, right = x/2+1;
int last_mid=0;
while(left<=right){
int mid = left+(right-left)/2;
if(x/mid>mid){ //不要x>mid*mid,会溢出
left=mid+1;
last_mid=mid;
} else if(x/mid<mid){ //不要x>mid*mid,会溢出
right = mid-1;
} else{
return mid;
}
}
int last_mid_1 = last_mid+1;
return (x-last_mid*last_mid)<(last_mid_1*last_mid_1-x)?last_mid:last_mid_1;
}
}
1、last_mid为x的平方根的向下取整,因为退出循环时肯定是left=right+1,即平方根在right到left之间,那么向下取整即为right。
2、(x-last_mid*last_mid)<(last_mid_1*last_mid_1-x)?last_mid:last_mid_1;用来判断这个平方根是离right近还是left近。