【问题标题】:How could I use a recursive method with an int parameter to return the number of zero digits in that int?如何使用带有 int 参数的递归方法来返回该 int 中的零位数?
【发布时间】:2012-11-01 00:51:01
【问题描述】:

方法是:

public static zeroCount(int num)

我的导师要求这个方法有一个 int 参数,递归方法必须返回 num 中零的个数。

所以 zeroCount(10200) = 3,并且 zeroCount(100300) = 4 等等……

我可以很容易地做到这一点,但因为我需要使用递归方法,所以我完全迷路了。

【问题讨论】:

    标签: java methods recursion


    【解决方案1】:

    提示:如果在每个递归步骤中不断将数字除以 10,如果没有余数则返回 1,如果有余数则返回 0?

    【讨论】:

      【解决方案2】:

      如果您可以迭代地解决问题(即使用某种循环),那么您可以递归地解决问题。

      编写递归方法时需要做的两件事是:

      • 基本案例;当你用尽了你的号码的所有数字时你会做什么,并且
      • 迭代案例;当你还有更多数字要走时,你会做什么。

      我还注意到您没有指定方法的返回值;理想情况下,它将是int。让这成为你的提示。

      【讨论】:

        【解决方案3】:

        您知道 x % 10 为您提供了 x 的最后一位数字,因此您可以使用它来识别零。此外,在检查特定数字是否为零之后,您想取出该数字,如何? 除以 10

        public static int zeroCount(int num)
        {
          int count = 0;
        
          if(num == 0) return 1;                  // stop case zeroCount(0)
          else if(Math.abs(num)  < 9)  return 0;  // stop case digit between 1..9 or -9..-1
          else
          {
           if (num % 10 == 0) // if the num last digit is zero
               count++; // count the zero, take num last digit out
        
           return count + zeroCount(num/10); // take num last digit out, and apply 
          } // the method recursively to the remaining digits 
        }
        

        我使用math.Abs​​来允许负数,你必须导入java.lang.Math;

        【讨论】:

          【解决方案4】:

          尝试以下方法:

          public int count0(int n) {
            if(n == 0) 
               return 0;
            if(n % 10 == 0) 
               return 1 + count0(n/10);
          
            return count0(n/10);
          } 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-03-03
            • 2014-02-28
            • 1970-01-01
            • 2019-09-24
            • 2012-09-21
            • 2020-06-26
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多