java recursive solution

  • 1

    An easy problem.There is no need to say much about it but the "mid".
    Considering the big integer,we should get it in this way.
    int mid = start+(end - start)/2;
    instead of
    int mid = (start+end)/2;
    here is the solution:

        public int guessNumber(int n) {
            return guessNumberRecursive(1,n);
        private int guessNumberRecursive(int start,int end) {
            if(start >= end) {
                return start;
            int mid = start+(end - start)/2;
            if (guess(mid) == 0) {
                return mid;
            }else if(guess(mid) > 0) {
                return guessNumberRecursive(mid+1,end);
            }else {
                return guessNumberRecursive(start,mid);

  • 0

    For the last return statement, it can be changed to

    return guessNumberRecursive(start, mid - 1);

    since the 'mid' is not in the correct guess anyway.

Log in to reply

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