Easy Java Solution using Binary Search. Type casting works faster then if/else statement.


  • 0
    O
    
        public int guessNumber(int n) {
            int low = 1;
            int mid = (n+low)/2;
            int g = guess(mid);
            while(g != 0) {
                if(g > 0) {
                    low = mid + 1;
                } else {
                    n = mid-1;
                }
                mid = (int)((double)n/2+(double)low/2);
                g = guess(mid);
            }
            
            return mid;
        }
    

  • 1
    A

    Somehow I managed to avoid integer overflow (was bitten also by it) without using double this way :

    public class Solution extends GuessGame {
        public int guessNumber(int n) {
            if(n == 1) return n;
            int l = 1, r = n;
            int mid = n/2;
            while( l < r) {
                int check = guess((int)mid);
                if(check == 0) return mid;
                if(check == 1) {
                    l = mid+1;
                } else {
                    r = mid-1;
                }
                mid = l + (r-l)/2;
            }
            return l;
        }
    }
    

Log in to reply
 

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