Skip to content

Commit cc08304

Browse files
authored
Create Guess Number Higher or Lower.java
1 parent 09de67b commit cc08304

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//374. Guess Number Higher or Lower
2+
/**
3+
* Forward declaration of guess API.
4+
* @param num your guess
5+
* @return -1 if num is higher than the picked number
6+
* 1 if num is lower than the picked number
7+
* otherwise return 0
8+
* int guess(int num);
9+
*/
10+
11+
public class Solution extends GuessGame {
12+
public int guessNumber(int n) {
13+
int l = 1;
14+
int r = n;
15+
16+
// Find the first guess num that >= target num
17+
while (l < r) {
18+
final int m = l + (r - l) / 2;
19+
if (guess(m) <= 0) // -1, 0
20+
r = m;
21+
else
22+
l = m + 1;
23+
}
24+
25+
return l;
26+
}
27+
}

0 commit comments

Comments
 (0)