[英]Having trouble understanding recursion in Java
import java.util.Scanner;
public class findFive {
public static int count = 0;
public static String result = null;
public static void main(String[] args) {
System.out.println("Enter a nonnegative number");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
countFive(number);
System.out.println(count);
}
public static void countFive(int number) {
if (number < 10) {// the base case
if (number == 5) {
count++;
}
} else { // number has two or more digits
countFive(number / 10);
if (number % 10 == 5) {
count++;
}
}
}
}
簡單地說,我不了解countFive(int number)
方法的流程。 我知道,如果用戶輸入5 ,則計數將簡單地等於1。但是,我的困惑來自於在方法內部再次使用“ countFive(number / 10)”調用該方法的地方。
編輯:如果有人通過像552這樣的數字進行編碼,我將不勝感激。
如果您想了解它是如何工作的,則應該逐步調試程序中的代碼,當您看到它在運行時,它將更加清晰
該方法計算數字5
在數字中出現了多少次。 例如,如果您輸入數字515
,則會發生以下情況
countFive(51)
countFive(number/10)
countFive(51)
countFive(5)
countFive(number/10)
countFive(5)
count
number%10 == 5
,其結果為1%10 == 5
錯誤 number%10 == 5
,得出5%10 == 5
是 增量count
countFive(515) | 515 greater than 10 | countFive(51) | | 51 greater than 10 | | countFive(5) | | | count++ | | 51 mod 10 does not equal 5 | 515 mod 10 equals 5 | count++
在遞歸中,創建基本情況是為了避免無限調用同一方法。 這是您在下面定義的。
if (number < 10) {// the base case
if (number == 5) {
count++;
}
}
如果滿足此條件,則執行此方法。 如果不正確,則執行else塊。
else { // number has two or more digits
countFive(number/10); //This is where it is called again
if (number%10 == 5) {
count++;
}
}
在此您可以調用countFive(number / 10)
好吧,該方法計算出5
個數字的出現次數。 例如, 5123512356
將返回3
。
您只需使用遞歸來刪除數字的最后一位,直到達到最高位(在左側示例中為5
)。
一旦已經達到了它,它會進入number < 10
,並認為它確實是一個5。然后將離開該方法,並用持續51
(51%10 = 1),與繼續512
, 5123
, 51235
( count++
)依此類推,直到與整數相乘為止。
需要說明的是:通過刪除原始數字的最后一位,直到不再不能將其除以10為止,才能調用number/10
以達到最高位數。 然后支票倒退。
讓我們看一個更簡單的示例: 5050
。
第一次調用: countFive(5050)
。 5050> 10,因此我們調用:
第二次調用: countFive(5050/10)
= countFive(505)
。 仍大於10
第三次致電: countFive(50)
第四次調用: countFive(5)
: counter++
,數字小於10現在我們向后瀏覽這三個調用(最后一個完成)
第三次通話: 50 % 10
= 0, counter
保持不變
第二次通話: 505 % 10
= 5, counter++
第一次通話: 5050 % 10
= 0, counter
保持不變
之后: counter
= 2。
讓我們接受您建議的輸入:552並遵循該方法。
起始計數為0。
number count number < 10 number == 5 number % 10 == 5
----------- ------- -------------- -------------- ------------------
552 0 false false false
55 0 false false true
1
5 1 true true true
2
它將返回2。基本上,您可以看到該方法對輸入中數字5
的出現次數進行計數。
您的基本情況將檢查它是否是一個數字( < 10
),如果是,則檢查該數字是否為5。否則,它將截斷最右邊的數字並再次調用該方法,就像輸入的是該新數字一樣。 一旦只剩下一位數字,它就會停止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.