Find a hidden number by repeatedly guessing and using higher/lower feedback.
Guess Number Higher or Lower
You are playing a guessing game with a hidden integer chosen from the range . Each time you make a guess, you receive feedback:
-1if your guess is higher than the hidden number1if your guess is lower than the hidden number0if your guess is exactly correct
Your task is to determine the hidden number using as few guesses as possible.
Assume you have access to an API guess(num) that returns the feedback above. Implement a function that finds the hidden number.
Input Format
- An integer
nrepresenting the inclusive upper bound of the search range. - An API
guess(num)that comparesnumwith the hidden number and returns-1,1, or0.
Output Format
Return the hidden number.
Constraints
- The hidden number is guaranteed to be in the range .
- You should minimize the number of calls to
guess(num).
Example 1
Input
n = 10, hidden number = 6
Output
6
Explanation
If you guess 5 and get 1, the hidden number is larger. If you then guess 8 and get -1, it is smaller. Continue narrowing the range until you find 6.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.