1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/java/guess-number-higher-or-lower.java
Matej Focko f6ac06990e
java: add «374. Guess Number Higher or Lower»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-08-15 20:05:14 +02:00

41 lines
900 B
Java

/**
* Forward declaration of guess API.
*
* @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 int guess(int num);
*/
class Solution extends GuessGame {
private enum Response {
Smaller(-1),
Exact(0),
Bigger(1);
public final int value;
private Response(int value) {
this.value = value;
}
}
public int guessNumber(int n) {
int lower = 1;
int upper = n;
while (true) {
var mid = lower + (upper - lower) / 2;
int response = guess(mid);
if (response == Response.Exact.value) {
return mid;
} else if (response == Response.Smaller.value) {
upper = mid - 1;
} else if (response == Response.Bigger.value) {
lower = mid + 1;
} else {
// invalid response
return -1;
}
}
}
}