log2N
public static void main(String[] args) {
int n = 3;
for (int i = 1; i <= 10; i++) {
System.out.println("输入:"+i);
turns(i, 1, 10);
}
}
private static int turns(int n, int low, int high) {
int turns = 0;
int guss = 0;
while (high - low >= 2) {
turns++;
int mid = (low + high) / 2;
guss = mid;
System.out.print(" 第"+turns+"次,我猜:"+guss);
if (mid == n) {
System.out.println(" 猜对了 end");
return turns;
} else if (mid < n) {
System.out.print(" 猜低了");
low = mid + 1;
} else {
System.out.print(" 猜高了");
high = mid - 1;
}
}
System.out.println("第"+(1 + turns)+"次"+" "+(guss+1) +" or "+(guss-1) +" end");
return 1 + turns;
}