Skip to content

Commit 0987eb1

Browse files
authored
Create guess-number-higher-or-lower.cpp
1 parent 12172b0 commit 0987eb1

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

C++/guess-number-higher-or-lower.cpp

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(logn)
2+
// Space: O(1)
3+
4+
// Forward declaration of guess API.
5+
// @param num, your guess
6+
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
7+
int guess(int num);
8+
9+
class Solution {
10+
public:
11+
int guessNumber(int n) {
12+
int left = 1, right = n;
13+
while (left <= right) {
14+
const auto mid = left + (right - left) / 2;
15+
if (guess(mid) <= 0) {
16+
right = mid - 1;
17+
} else {
18+
left = mid + 1;
19+
}
20+
}
21+
return left;
22+
}
23+
};

0 commit comments

Comments
 (0)