mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
42 lines
900 B
Java
42 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;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|