
Guess the Number Higher or Lower
Guess the Number Higher or Lower Problem Statement We are playing a guessing game. The system picks a number between 1 and n. Your task is to guess the number. You are given an API called guess which returns -1 if your guess is higher than the picked number 1 if your guess is lower than the picked number 0 if your guess is correct Find the picked number. Example Input n = 10 picked number = 6 Output 6 Approach Using Binary Search The idea is to reduce the search space by half in each step. Steps 1 Start with the range from 1 to n 2 Find the middle value 3 Call guess with the middle value 4 If result is 0 return the number 5 If result is -1 search in the left half 6 If result is 1 search in the right half 7 Repeat until the number is found Code ```python id="guess1" The guess API is already defined def guess(num): def guessNumber(n): left = 1 right = n while left <= right: mid = (left + right) // 2 result = guess(mid) if result == 0: return mid elif result == -1: right = mid - 1 else: l
Continue reading on Dev.to
Opens in a new tab



