码迷,mamicode.com
首页 > 其他好文 > 详细

猜数游戏

时间:2016-07-01 18:23:59      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

猜数游戏

标签:

原文地址:http://www.cnblogs.com/shixm/p/5633929.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!