1 ms JAVA solution using range instead of (end-start)/2

  • 0

    The idea here is that, in every check, the value range shrinks by 2. I use double to store the range to make it precise.
    Until result is 0, the number is found.

        public int guessNumber(int n) {
            if(guess(1) == 0) return 1;
            //n indicate next check point, which is located at the middle of that range
            int res = guess(n);
            double range = (n+1)/2;
            while(res != 0){
                    case 1:
                        n += range;
                    case -1:
                        n -= range;
                res = guess(n);
                //range+1 includes the edge
            return n;

Log in to reply

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