Leetcode thematic dichotomy of -374 numberguess size (374. Guess Number Higher or Lower)

Leetcode thematic dichotomy of -374 numberguess size (374. Guess Number Higher or Lower)


 

We're playing a guessing game. Rules of the game are as follows:
I am from 1 to  n  select a number. I guess you need to choose which number.
Every time you guess wrong, I'll tell you this figure is big or small.
You call a pre-defined interfaces  guess(int num), it will return three possible outcomes ( -1, 1 or  0):

-1: I have a relatively small number 
 1: I figure larger 
 0: Congratulations! you guessed right!

Example:

Input: n = 10, pick = 6 
Output: 6

Similar topics: . Dichotomy topic Leetcode first error of -278 version (First Bad Version)
solution to a problem this question see the link above, the idea is the same.

AC Code:
/* The guess API is defined in the parent class GuessGame.
   @param num, your guess
   @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
      int guess(int num); */

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int L = 1;
        int R = n;
        while(L<R){
            int mid = (L+R)>>>1;
            int guessAns = guess(mid);
            if(guessAns==1){
                L = mid+1;
            }else{
                R = mid;  
            }
        }
        return L;
    }
}

 



Guess you like

Origin www.cnblogs.com/qinyuguan/p/11415921.html