繁体   English   中英

我如何使用带有int参数的递归方法返回该int中的零位数?

[英]How could I use a recursive method with an int parameter to return the number of zero digits in that int?

方法是:

public static zeroCount(int num)

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

所以zeroCount(10200)= 3,而zeroCount(100300)= 4等...

我可以轻松地做到这一点,但因为我需要使用递归方法,所以我完全迷失了。

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

如果你可以迭代地处理问题(也就是说,使用某种循环),那么你可以递归地完成它。

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

  • 基础案例 ; 当你用尽所有数字的数字时你会怎么做,以及
  • 一个迭代的案例 ; 当你还有更多的数字时你会怎么做。

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

您知道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;

请尝试以下方法:

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

  return count0(n/10);
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM