https://leetcode-cn.com/problems/guess-number-higher-or-lower/
我的解法:
public static int guessNumber(int n) {
int left = 0;
int right = n;
int mid = left + (right-left)/2;
while(guess(mid)!=0){
int result = guess(mid);
if(result<0){
right = mid-1;
}else if(result>0){
left = mid+1;
}else{
return mid;
}
mid = left + (right-left)/2;
}
return mid;
}
官方解法:
public static int guessNumber(int n) {
while(left<=right){
int mid = left + (right-left)/2;
int result = guess(mid);
if(result<0){
right = mid-1;
}else if(result>0){
left = mid+1;
}else{
return mid;
}
}
return -1;
}