java: add «374. Guess Number Higher or Lower»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
e54bc40aca
commit
f6ac06990e
1 changed files with 41 additions and 0 deletions
41
java/guess-number-higher-or-lower.java
Normal file
41
java/guess-number-higher-or-lower.java
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue