Self-explained Solution #Java #binary-search


  • 1
    /* 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 m = l + (r-l)/2;
                int guessResult = guess(m);
                
                if (guessResult == 0) return m;
                else if (guessResult == 1) l = m+1;
                else r = m-1;
            }
            
            // should never reach
            // #1. Log warning messages
            // #2. assert 0 == -1
            return 0;
        }
    }
    

  • 1
    H

    How should we warn the client if the program reaches the bottom, which is an unintended consequence.


  • 1
    1. Print out warning/error messages
    2. Assertion
    3. Return explicit error result

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.