我知道如何计算数字的阶乘,但是我希望显示内存中正在调用的内容。所以使用递归的阶乘就像休耕一样
public static long factorial(int n) {
if (n == 1) return 1;
return n * factorial(n-1);
}
我希望实现以下
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120
我已经到了这一点......我在显示方法的递归返回时遇到了麻烦(第二部分)
public static long factorial(int n) {
System.out.println("factorial("+n+")");
if (n == 1) {
System.out.println("return 1");
return 1;
}
return n * factorial(n-1);
}
答案 0 :(得分:3)
返回前尝试打印:
public static long factorial(int n) {
System.out.println("factorial("+n+")");
if (n <= 1) { // factorial(0) = factorial(1) = 1
System.out.println("return 1");
return 1;
}
long fac = factorial(n-1);
System.out.printf("return %d * %d = %d%n", n, fac, n * fac);
return n * fac;
}
要获得每行n个空格,您可以添加一个辅助函数,该函数接收当前的&#34;深度&#34;递归和打印n空间相应。
// public function visible to the world
public static long factorial(int n) {
return factorial(5, 0);
}
// helper function that takes in the current depth of
// the recursion
private static long factorial(int n, int depth) {
String spaces = repeat(' ', depth);
System.out.print(spaces);
System.out.println("factorial("+n+")");
if (n <= 1) { // factorial(0) = factorial(1) = 1
System.out.println(spaces + " return 1");
return 1;
}
long fac = factorial(n-1, depth + 1);
System.out.print(spaces);
System.out.printf("return %d * %d = %d%n", n, fac, n * fac);
return n * fac;
}
// helper function to create a String by repeating
// char c, n times.
private static String repeat(char c, int times) {
char[] sequence = new char[times];
Arrays.fill(sequence, c);
return new String(sequence);
}
答案 1 :(得分:2)
您可以使用try {} finally {}块来执行某些操作&#34;&#34;它已被退回
public static long factorial(int n) {
try {
System.out.println("factorial(" + n + ")");
if (n == 1) {
System.out.println("return 1");
return 1;
}
return n * factorial(n - 1);
} finally {
System.out.println("return " + n);
}
}