【发布时间】:2012-11-01 00:51:01
【问题描述】:
方法是:
public static zeroCount(int num)
我的导师要求这个方法有一个 int 参数,递归方法必须返回 num 中零的个数。
所以 zeroCount(10200) = 3,并且 zeroCount(100300) = 4 等等……
我可以很容易地做到这一点,但因为我需要使用递归方法,所以我完全迷路了。
【问题讨论】:
方法是:
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);
}
【讨论】: