# July 5th 2023

## Problem Description permalink

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to 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.

## Solution permalink

`/**`

* Forward declaration of guess API.

* @param {number} 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

* var guess = function(num) {}

*/

function guessNumber(n: number): number {

if (n == 1){

return 1

}

let lowerBound = 0;

let upperBound = n;

let guessNum = lowerBound + Math.floor((upperBound - lowerBound) / 2)

let guessResult = guess(guessNum);

while (lowerBound >= 0 && upperBound <= n ){

if (guessResult === -1){

upperBound = guessNum - 1;

} else if (guessResult == 1){

lowerBound = guessNum + 1

} else {

return guessNum

}

guessNum = lowerBound + Math.floor((upperBound - lowerBound) / 2)

guessResult = guess(guessNum);

}

return 0

};