# 374.guess-number-higher-or-lower

## Statement

• Difficulty: Easy
• Tag: `二分查找` `交互`

• 每轮游戏，我都会从 1 到 n 随机选择一个数字。 请你猜选出的是哪个数字。
• 如果你猜错了，我会告诉你，你猜测的数字比我选出的数字是大了还是小了。

• -1：我选出的数字比你猜的数字小 `pick < num`
• 1：我选出的数字比你猜的数字大 `pick > num`
• 0：我选出的数字和你猜的数字一样。恭喜！你猜对了！`pick == num`

``````输入：n = 10, pick = 6

``````

``````输入：n = 1, pick = 1

``````

``````输入：n = 2, pick = 1

``````

``````输入：n = 2, pick = 2

``````

• `1 <= n <= 231 - 1`
• `1 <= pick <= n`

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 will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API `int guess(int num)`, which returns three possible results:

• `-1`: Your guess is higher than the number I picked (i.e. `num > pick`).
• `1`: Your guess is lower than the number I picked (i.e. `num < pick`).
• `0`: your guess is equal to the number I picked (i.e. `num == pick`).

Return the number that I picked.

Example 1:

``````Input: n = 10, pick = 6
Output: 6
``````

Example 2:

``````Input: n = 1, pick = 1
Output: 1
``````

Example 3:

``````Input: n = 2, pick = 1
Output: 1
``````

Constraints:

• `1 <= n <= 231 - 1`
• `1 <= pick <= n`

## Solution

``````# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:

from bisect import bisect_left

class Solution:
def guessNumber(self, n: int) -> int:
return bisect_left(range(n + 1), 0, 1, key=lambda x: -guess(x))
``````