题目链接:https://leetcode.com/problems/guess-number-higher-or-lower/description/
猜数字大小,返回1表示小了,-1表示大了,0表示正确
跟昨天写的704差不多
int guess(int num);
class Solution {
public:
int guessNumber(int n) {
int l = 1;
int r = n;
int ans = -1;
int mid;
while(l < r){
mid = l / 2 + r / 2;
if(guess(mid) == 0){
ans = mid;
break;
}else if(guess(mid) == 1){
l = mid+1;
}else if(guess(mid) == -1){
r = mid;
}
}
if(ans == -1){
if(guess(1) == 0){
ans = 1;
}else if(guess(n) == 0){
ans = n;
}
}
return ans;
}
};