1 题目
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num)
which returns 3 possible results (-1
, 1
, or 0
):
-1 : My number is lower
1 : My number is higher
0 : Congrats! You got it!
Example :
Input: n = 10, pick = 6
Output: 6
2 尝试解
2.1 分析
猜数字,在给定范围猜数字。二分法应用。题目描述的不是很清楚,My number指的是要要猜的答案。
2.2 代码
class Solution {
public:
int guessNumber(int n) {
long low = 1;
long high = n;
long mid = (low+high)/2;
while(guess(mid)!= 0 && low < high){
if(guess(mid)==1) low = mid+1;
else high = mid;
mid = (high + low)/2;
}
return mid;
}
};
3 标准解
int guessNumber(int n) {
int maxNumber = n, minNumber = 1;
while (true) {
int meanNumber = (maxNumber - minNumber) / 2 + minNumber;
// Do NOT use (maxNumber+minNumber)/2 in case of over flow
int res = guess(meanNumber);
if (res == 0) {
return meanNumber;
} else if (res == 1) {
minNumber = meanNumber + 1;
} else {
maxNumber = meanNumber - 1;
}
}
}