Search code examples
javarecursionmethodsreturn

How to exit from a method, i.e how can i return from a function in this recursion in java?


How to exit from a method, i.e how can i return from a function in this recursion in java?

public class solution {

    public static int countZerosRec(int input){

      int n=0;
      int k =0;
      int count=0;
      //Base case
      if(n==0)
      {
        return; // How can i return the method from here, i.e how can i stop the execution of the recursive program now.
      }

      k=input%10;
      count++;
      n=input/10;
      countZerosRec(n);
      int myans=count;
      return myans;


    }
}

Please help me getting out of this method. This is a program to count number of zeroes.

Example, 34029030 ans = 3


Solution

  • You can try below approach:

    public class MyClass {
        public static void main(String args[]) {
    
    
            System.out.println("total zeroes = " + returnZeroesCount(40300));
        }
        public static int returnZeroesCount(int input){
            if(input == 0)
                return 0;
            int n = input % 10;
            return n == 0 ? 1 + returnZeroesCount(input / 10) : returnZeroesCount(input / 10);
        }
    }
    

    How it works: Assuming your input > 0, we try to get the last digit of the number by taking the modulus by 10. If it is equal to zero, we add one to the value that we will return. And what will be the value that we would be returning? It will be the number of zeroes present in the remaining number after taking out the last digit of input.

    For example, in the below case, 40300: we take out 0 in first step, so we return 1+number of zeroes in 4030. Again, it appears as if we have called our recursive function for the input 4030 now. So, we again return 1+number of zeroes in 403.

    In next step, since last number is 3, we simply return 0+total number of zeroes in 40 or simply as total number of zeroes present in 40 and so on.

    For ending condition, we check if the input is itself 0. If it is zero then this means that we have exhausted the input number and there are no further numbers to check for. Hence, we return zero in that case. Hope this helps.