why would I get StackOverFlow error?


  • 0
    S

    why would I get StackOverFlow error?
    I really don't know why the recursion does not terminate

    public class Solution extends GuessGame {
        public int guessNumber(int n) {
            return help(1, n);
        }
        
        public int help(int s, int e){
           int mid = (s + e)/2;
           if (guess(mid) == 0){
               return mid;
           }else if (guess(mid) > 0){
               return help(s, mid - 1);
           }else{
               return help(mid + 1, e);
           }
            
          
        }
    }
    

  • 1
    V

    I think you have 2 problems here

    1. when guess(mid)>0 , it means the target number is higher than your guess, so you should call help(mid+1,e) in that case. Similar error with the case when guess(mid) < 0.
    2. the StackOverFlow happens because (s+e) could be larger than the max integer. Change it to "int mid = s+(e-s)/2" should solve the problem.

  • 0
    S

    Thanks ! It is solved now.


  • 0
    Z

    Cause guess(n) == -1 means n > target number.
    guess(n) == 1 means n<target number.
    You reversed them.


Log in to reply
 

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