java: add «374. Guess Number Higher or Lower»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-15 20:05:14 +02:00
parent e54bc40aca
commit f6ac06990e
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,41 @@
/**
* 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;
}
}
}
}