## Algorithm

Problem Name: 374. Guess Number Higher or Lower

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.

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

• `1 <= n <= 231 - 1`
• `1 <= pick <= n`

## Code Examples

### #1 Code Example with Java Programming

```Code - Java Programming```

``````
public class Solution extends GuessGame {
public int guessNumber(int n) {
int start = 1;
int end = n;
while (start <= end) {
int mid = start + (end - start) / 2;
int result = guess(mid);
if (result == -1) {
end = mid - 1;
} else if (result == 1) {
start = mid + 1;
} else {
return mid;
}
}
return -1;
}
}
``````
Copy The Code &

Input

cmd
n = 10, pick = 6

Output

cmd
6

### #2 Code Example with C# Programming

```Code - C# Programming```

``````
namespace LeetCode
{

public class _0374_GuessNumberHigherOrLower
{

public _0374_GuessNumberHigherOrLower(int number)
{
this.number = number;
}

public int GuessNumber(int n)
{
int lo = 1, hi = n;
while (lo <= hi)
{
var mid = lo + (hi - lo) / 2;

var compare = guess(mid);
if (compare == 0) return mid;
else if (compare == -1) hi = mid - 1;
else lo = mid + 1;
}

return -1;
}

private int guess(int num)
{
if (num < number) return 1;
else if (num > number) return -1;
else return 0;
}
}
}
``````
Copy The Code &

Input

cmd
n = 10, pick = 6

Output

cmd
6