-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_374_GuessNumHigherOrLower.cpp
47 lines (42 loc) · 1.1 KB
/
LC_374_GuessNumHigherOrLower.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
https://leetcode.com/problems/guess-number-higher-or-lower/
374. Guess Number Higher or Lower
*/
/**
* 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 {
public:
int guessNumber(int n) {
int low=1, high = n, mid;
while(low<=high)
{
mid = low + ((high-low)>>1);
// switch(guess(mid))
// {
// case -1:
// high = mid-1;
// break;
// case 1:
// low = mid+1;
// break;
// case 0:
// return mid;
// break;
// }
int pick = guess(mid);
if(pick == 0)
return mid;
else if(pick == 1)
low = mid+1;
else
high = mid-1;
}
return -1;
}//end
};