Problem
In this game, a number is picked between 1 and n.
You must guess the number using the API guess(num).
The API returns:
-1 → your guess is higher
1 → your guess is lower
0 → your guess is correct
Your task is to find the picked number.
Example
Input
n = 10
pick = 6
Output
6
Approach
We can use Binary Search:
Start with low = 1 and high = n
Find middle value
Check the result using guess(mid)
Adjust search range until the correct number is found
Python Code
class Solution:
def guessNumber(self, n: int) -> int:
low = 1
high = n
while low <= high:
mid = low + (high - low) // 2
res = guess(mid)
if res == 0: # Correct guess
return mid
elif res < 0: # Guess is higher than the pick
high = mid - 1
else: # Guess is lower than the pick
low = mid + 1
Output
6
Top comments (0)