public int count7(int n)
{
int count = 0;
if (n%10 == 7) count= 1;
if(n%10 != 7) count= 0;
if (n < 10 && n==7) return 1;
if (n < 10 && n!=7) return 0;
else return count7(n/10) + count;
}
我有上述函數遞歸地添加7在給定數字中的出現次數。每次它將數字除以10以減少1個數字並檢查最後一個數字是否等於7.遞歸函數與本地變量不執行,如果語句
當我將它作爲count7(7)運行時,它返回1.我有一個問題,它爲什麼從未命中第一if語句(if n%10 == 7) count = 1;
如果我的計劃是寫爲:
public int count7(int n)
{
int count = 0;
if (n%10 == 7) count= 0;
if(n%10 != 7) count= 0;
if (n < 10 && n==7) return 1;
if (n < 10 && n!=7) return 0;
else return count7(n/10) + count;
}
呼叫count7(7)仍能正常工作。我的問題是,當遞歸調用放在堆棧上時,爲什麼最後一次調用沒有將count賦值爲1,而是將其賦值爲0?
例如:
Count7(717)
Count7(7) + count <-------This hits the base case since n < 10
Count(71) + count
Count(717) + count
計數被分配1每當ñ%10 == 7.但鹼情況下,也將返回1,因爲它是請解釋此一例只有我無法正確理解的事情。
另外「if(n <10 && n == 7)」是多餘的。 – DJClayworth
逐行掃描代碼。在你走的時候,把每個變量的值寫在一張紙上(記住跟蹤所有不同的'count'實例)。 – DJClayworth
你的第二個代碼是否適用於count(717)? – lmcphers