Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f46c110

Browse files
committed
2017/4/3
1 parent 60dbc94 commit f46c110

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

No374_GuessNumberHigherorLower.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// We are playing the Guess Game. The game is as follows:
2+
3+
// I pick a number from 1 to n. You have to guess which number I picked.
4+
5+
// Every time you guess wrong, I'll tell you whether the number is higher or lower.
6+
7+
// You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
8+
9+
// -1 : My number is lower
10+
// 1 : My number is higher
11+
// 0 : Congrats! You got it!
12+
// Example:
13+
// n = 10, I pick 6.
14+
15+
// Return 6.
16+
17+
18+
// Forward declaration of guess API.
19+
// @param num, your guess
20+
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
21+
int guess(int num);
22+
23+
class Solution {
24+
public:
25+
// Pay attentation of My number, "My" here means the unknown number
26+
int guessNumber(int n) {
27+
int low = 1, high = n;
28+
int guess_num = 0;
29+
while(true){
30+
// Overflow
31+
//guess_num = (low + high) / 2;
32+
guess_num = (high-low)/2 + low;
33+
int flag = guess(guess_num);
34+
if(flag == 0){
35+
return guess_num;
36+
}
37+
else if(flag > 0){
38+
low = guess_num + 1;
39+
}
40+
else{
41+
high = guess_num - 1;
42+
}
43+
44+
}
45+
}
46+
};

0 commit comments

Comments
 (0)