如何退出方法,即如何从java中的递归函数返回?

问题描述 投票:0回答:5

如何退出方法,即如何从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;


    }
}

请帮我摆脱这种方法。这是一个计算零数的程序。

例如,34029030岁= 3

java recursion methods return
5个回答
1
投票

您可以尝试以下方法:

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);
    }
}

它是如何工作的:假设你的input > 0,我们试图通过将模数乘以10得到数字的最后一位数。如果它等于零,我们在我们将返回的值上加一。我们将返回的价值是什么?取出input的最后一位数后,它将是剩余数字中的零个数。

例如,在下面的例子中,40300:我们在第一步中取0,所以我们在4030中返回1 +零个数。再次,看起来好像我们现在为输入4030调用了递归函数。所以,我们再次在403中返回1 +个零。

在下一步中,由于最后一个数字是3,我们简单地返回0 + 40中的零总数或者仅仅作为40中存在的零的总数,依此类推。

对于结束条件,我们检查输入本身是否为0.如果它为零,那么这意味着我们已经耗尽了输入数字,并且没有其他数字要检查。因此,在这种情况下我们返回零。希望这可以帮助。


0
投票

如果您主要关注的是查找给定数字中的零个数,则可以使用此选项:

     int numOfZeroes =0;
     long example = 670880930;
     String zeroCounter = String.valueOf(example);
     for(int i=0; i< example.length();i++){
         if(zeroCounter.charAt(i) ==0){
             numOfZeroes++;
         }

     }
      System.out.print("Num of Zeros are"+ numOfZeroes);` `

0
投票

我会发布一些指示让你感动,而不是在你的问题上发布代码答案。

  1. 正如@jrahhali所说,正如你的代码那样,它不会超过return块中的if语句(这是一个错误BTW,因为你有一个int返回类型)。
  2. 我建议你将最后两行移动到某个调用函数(例如main方法)。这样,所有这个功能都需要做的是做一些基本的处理并继续前进。
  3. 你根本没有检查k。事实上,你的count总会增加。

希望这足以让你解决问题。


0
投票
int count =0;
private int getZeroCount(int num){
         if(num+"".length == 1){
                  if(num==0){
                        count++;
                  }
                  return count;
         }
         if(num%10 == 0){
                  count++;
         }
         num /= 10;
         getZeroCount();

}


-2
投票

方法1:

public static int countZero1(int input) {
    int count = 0;
    //The loop takes the remainder for the value of the input, and if it is divided by 10, then its number of digits is 0.
    // When the value of the input is less than 0, the cycle ends
    while (input >0){
        if (input % 10 == 0){
            count ++;
        }
        input /= 10;
    }
    return count;
}

方法2:

private static int count = 0;
public static int countZero2(int input) {
    //Recursive call function
    if (input % 10 == 0){
        count ++;
    }
    input /= 10;
    if (input <= 0){
        return count;
    }else {
        return countZero2(input);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.