Guess Number Higher or Lower

Easy

We are playing the Guess Game. I pick a number from 1 to n, and you have to guess which number I picked.

Every time you guess wrong, I tell you whether the number I picked is higher or lower than your guess.

You find out through a pre-defined API, guess(num), which returns one of three results:

  • -1: your guess is too high (num > pick).
  • 1: your guess is too low (num < pick).
  • 0: your guess is right (num == pick).

Return the number that I picked.

Examples

Example 1

Input:  n = 10, pick = 6
Output: 6

One way to get there: guess(5) returns 1 (too low), so the pick is in 6–10. guess(8) returns -1 (too high), so it's in 6–7. guess(6) returns 0.

Example 2

Input:  n = 1, pick = 1
Output: 1

There's only one possible number.

Example 3

Input:  n = 2, pick = 1
Output: 1

Example 4

Input:  n = 2147483647, pick = 2147483647
Output: 2147483647

n is the largest 32-bit integer. With both ends of the range this high, (low + high) / 2 overflows an int in Java, C++ and C.

Constraints

  • 1 <= n <= 2^31 - 1
  • 1 <= pick <= n

How the tests work: each test lists n and pick, but your function only receives n. The only way to learn pick is to call guess. In TypeScript, Python, C and C++, guess is a global function; in Java, Solution extends GuessGame, which provides it. More than 100 calls to guess fails the test.

TypeScript
Loading editor…
Test cases33
Case 1
n = 10
pick = 6
Case 2
n = 1
pick = 1
Case 3
n = 2
pick = 1
Case 4
n = 2
pick = 2
Case 5
n = 3
pick = 1
Case 6
n = 3
pick = 2
Case 7
n = 3
pick = 3
Case 8
n = 10
pick = 1
Case 9
n = 10
pick = 10
Case 10
n = 100
pick = 50
Case 11
n = 100
pick = 1
Case 12
n = 100
pick = 100
Case 13
n = 1000
pick = 777
Case 14
n = 2147483647
pick = 2147483647
Case 15
n = 2147483647
pick = 2147483646
Case 16
n = 2147483647
pick = 1
Case 17
n = 2147483647
pick = 1073741824
Case 18
n = 2147483647
pick = 1702766719
Case 19
n = 2147483646
pick = 2147483646
Case 20
n = 2126753390
pick = 1702766719
Case 21
n = 1000000000
pick = 999999999
Case 22
n = 1906061198
pick = 249432148
Case 23
n = 1590309877
pick = 1150502114
Case 24
n = 2093562149
pick = 1704575015
Case 25
n = 1462902606
pick = 748266613
Case 26
n = 34359523
pick = 14767635
Case 27
n = 97546539
pick = 48787618
Case 28
n = 531241486
pick = 482009049
Case 29
n = 2131944185
pick = 770186046
Case 30
n = 1919486233
pick = 1115152246
Case 31
n = 13
pick = 9
Case 32
n = 10
pick = 7
Case 33
n = 7
pick = 2