VISUALGO//PROBLEMS
guess number higher or lower · binary searcheasy
LeetCode #374
range [1, 10] — pick: 6
1
2
3
4
5
6
7
8
9
10
found
·
ELEMENTS
n
pick
Python
def guessNumber(n: int) -> int:
    low, high = 1, n

    while low <= high:
        mid = (low + high) // 2
        result = guess(mid)  # -1, 0, or 1

        if result == 0:
            return mid
        elif result == -1:
            high = mid - 1
        else:
            low = mid + 1

    return -1