Very Simple Recursion but stack overflow, Can everyone help me?


  • 0
    H
    public int guessNumber(int n) {
            return tryo(1, n);
        }
        
        public int tryo(int low, int high){
            int ans = -1;
            int mid = (low + high) / 2;
            
            if(guess(mid) == 0) ans = mid;
            if(guess(mid) == 1) ans = tryo(mid+1, high);
            if(guess(mid) == -1) ans = tryo(low, mid-1);
            
            return ans;
        }

  • 0

    You can't use ( low + high ) / 2 cuz it will cause overflow
    You should use low + ( high - low ) / 2 instead.


  • 0
    H

    Thank you !Thank you !Thank you !


Log in to reply
 

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