在范围[low,high]之间猜数字的Java代码
//当n确认在范围[low,high]时,计算需要猜测的次数
// 当n确认在范围[low,high]时,计算需要猜测的次数
public static int turns(int n,int low,int high){
int turns = 0;
// 如果还有潜在的数字需要猜测,则继续
while (high >= low){
turns++;
int mid = (low + high)/2;
if (mid == n){
return turns;
}else if (mid < n){
low = mid + 1;
}else {
high = mid -1;
}
}
System.out.println(turns);
return turns;
}
public static void main(String[] args) {
int cishu = turns(8,0,100000);
System.out.println(cishu);
}
运行结果

907

被折叠的 条评论
为什么被折叠?



