Guess Number Higher or Lower

来源:互联网 发布:java参数传递 编辑:程序博客网 时间:2024/05/17 07:11

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I'll tell you whether the number is higher or lower.

You call a pre-defined API guess(int num) which returns 3 possible results (-11, or 0):

-1 : My number is lower 1 : My number is higher 0 : Congrats! You got it!

Example:

n = 10, I pick 6.Return 6.

采用二分法,迭代的写法。题目讲的不是很清楚,而且那个api返回的是目标值跟目前二分的值相比的结果,实现的时候弄反了。 而且还需要注意溢出的情况,计算mid的时候,要用start+(end-start)/2, start+end可能会溢出。


代码:

public int guessNumber(int n) {        int start = 1;        int end = n;        while(start<=end){            int mid = start+ (end-start)/2;//注意会溢出            if(guess(mid) == 0) return mid;            if(guess(mid) == -1){                end = mid -1;            }            else{                start = mid +1;            }        }        return -1;    }


0 0