-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuessNumberHigherorLower_374.cpp
More file actions
executable file
·40 lines (36 loc) · 1.19 KB
/
GuessNumberHigherorLower_374.cpp
File metadata and controls
executable file
·40 lines (36 loc) · 1.19 KB
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
#include <cstdlib>
#include <iostream>
// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);
class Solution {
public:
int guessNumber(int n) {
int top = n;
int buttom = 0;
int m = (top - buttom) / 2; //m is the middle numder
cout << "m = " << m << endl;
while (true)
{
if (guess(m) == 0)
break;
else if (guess(m) == -1) // my guess is too high
{
top = m;
m = (top - buttom) / 2; //m is the middle numder
cout << "m was too high, now m = " << m << endl;
}
else if (guess(m) == 1)//my guess is too low
{
cout << "top = " << top << endl;
cout << "buttom = " << buttom << endl;
cout << "m = " << m << endl;
buttom = m;
m = floor((top - buttom) / 2 + buttom);
cout << "m was too low, now m = " << m << endl;
}
}
return (m);
}
};