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 APIguess(int num)which returns 3 possible results (-1,1, or0):

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

Example:

n = 10, I pick 6.

Return 6.

题目大意:

我们来玩猜数字游戏。游戏规则如下:

我挑选一个1到n之间的数字。你来猜我选的是哪个数字。

每一次你猜错,我都会告诉你数字高了还是低了。

你可以调用一个预定义的API guess(int num),返回3种结果 (-1, 1, 或 0):

-1 : 我的数字更低
 1 : 我的数字更高
 0 : 恭喜你!猜对了!

测试用例如题目描述。

解题思路:

二分查找(Binary Search)

Last updated

Was this helpful?