描述
给出一个数,让你猜这个数,有一个辅助函数guess()作判断,直接调用即可。
解决
二分判断。用 int m = (l + r) >> 1
就超时,然后换成了int m = l + (r - l) / 2
然后就过了
// 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 l = 1, r = n;
while (l < r){
int m = l + (r - l) / 2;
int res = guess(m);
//cout << res << endl;
if (res == 0){
return m;
}
else if (res == 1){
l = m + 1;
}
else if (res == -1){
r = m - 1;
}
}
return l;
}
};