我試圖更好地理解 Java 的遞回,我正在做一個使用迭代、頭尾遞回的程式。它應該計算不同方法呼叫了多少次。我應該在頭部和尾部添加什么來完成程式?先感謝您
public static void main(String[] args) {
}
private static int fibIt(int n) {
switch (n) {
case 0:
return 0;
case 1:
return 1;
}
int a = 0;
int b = 1;
for (int i = 2; i <= n; i ) {
b = a b;
a = b - a;
}
return b;
}
private static int fibHr(int n) {
switch (n) {
case 0:
return 0;
case 1:
return 1;
default:
return fibHr(n - 1) fibHr(n - 2);
}
}
private static int fibTr(int n) {
return fibTr(0, 1, n);
}
private static int fibTr(int a, int b, int n) {
switch (n) {
case 0:
return a;
case 1:
return b;
default:
return fibTr(b, a b, n - 1);
}
}
uj5u.com熱心網友回復:
您可以將每個方法轉換為類的實體方法,然后將計數器保存在私有欄位中,并使用 getter 來公開值。
public class HeadRecursion {
private long counter = 0;
public int fib(int n) {
counter;
switch (n) {
case 0:
return 0;
case 1:
return 1;
default:
return fibHr(n - 1) fibHr(n - 2);
}
}
public long getCounter() { return count; }
}
然后你可以實體化你的類,運行你的函式,然后獲取并輸出計數器:
public static void main() {
final var obj = new HeadRecursion();
obj.fib(10);
System.out.println(obj.getCounter());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/421127.html
標籤:
