Guess Num Higer Or Lower
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):
Have you met this question in a real interview?
Example
n = 10, I pick 4 (but you don't know)
Return 4. Correct !
public class Solution extends GuessGame {
/**
* @param n an integer
* @return the number you guess
*/
public int guessNumber(int n) {
// Write your code here
//be careful, -1 is my number is lower which means mid is larger than the target number ,need to move end to mid
int start = 0, end = n;
while(start + 1 < end){
int mid = start + (end - start)/2;
if(guess(mid) == 0){
return mid;
}else if(guess(mid) == -1){
end = mid;
}else{
start = mid;
}
}
System.out.println(start+" "+end);
if(guess(start) == 0){
return start;
}
if(guess(end) == 0){
return end;
}
return -1;
}
}
Last updated