We are playing the Guess Game. The game is as follows:
I pick a number from
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.
Input: n = 10, pick = 6 Output: 6
Input: n = 1, pick = 1 Output: 1
Input: n = 2, pick = 1 Output: 1
1 <= n <= 231 - 1
1 <= pick <= n
Memory Usage: 14 MB, less than 16.19% of Python3 online submissions for Guess Number Higher or Lower.
# The guess API is already defined for you. # @param num, your guess # @return -1 if num is higher than the picked number # 1 if num is lower than the picked number # otherwise return 0 # def guess(num: int) -> int: class Solution: def guessNumber(self, n: int, low = 0) -> int: mid = (n+low)//2 updown = guess(mid) if updown == 0: return mid elif updown == 1: return self.guessNumber(n, mid+1) else: return self.guessNumber(mid-1,0)