LeetCode Guess Number Higher or Lower

LeetCode Guess Number Higher or Lower

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 (-1, 1, 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.

简单的猜数字游戏。使用二分搜索就好。唯一需要注意的是,题目中的guess函数中说My number is lower/higher是指正确答案比中值低或高,而不是我们猜的中值比正确答案低或高。唉,这算是题目描述不清吧,为此WA两次。

代码如下:

int guess(int num);
class Solution {
public:
	int guessNumber(int n) {
		int l = 1, r = n, mid = l + (r - l) / 2;
		int g = guess(mid);
		while (g != 0) {
			if (g == -1)r = mid - 1;
			else l = mid + 1;
			mid = l + (r - l) / 2;
			g = guess(mid);
		}
		return mid;
	}
};

本代码提交AC,用时0MS。

Leave a Reply

Your email address will not be published. Required fields are marked *