Guess Number Higher or Lower
2018-09-10 本文已影响0人
BLUE_fdf9
题目
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):
答案
public class Solution extends GuessGame {
public int guessNumber(int n) {
int left = 1, right = n;
while(left <= right) {
int mid = left + (right - left) / 2;
int ret = guess(mid);
if(ret == 0) return mid;
else if(ret == -1) {
// go left
right = mid;
}
else {
left = mid + 1;
}
}
return 0;
}
}