【发布时间】:2017-02-17 09:06:16
【问题描述】:
我正在尝试通过查看示例来提高我的递归技能(阅读书面递归函数)。但是,我可以很容易地得到没有局部变量的递归逻辑。在下面的示例中,我无法理解 total 变量是如何工作的。我应该如何看待使用局部变量来读写的递归函数?我认为它就像堆栈回击。顺便说一句,我写的例子没有变量。我试图只写countThrees(n / 10); 而不是total = total + countThrees(n / 10);,但它不起作用。
带有total 变量:
int countThrees(int n) {
if (n == 0) { return 0; }
int lastDigit = n % 10;
int total = 0;
total = total + countThrees(n / 10);
if (lastDigit == 3) {
total = total + 1;
}
return total;
}
简化版
int countThrees(int x)
{
if (x / 10 == 0) return 0;
if (x % 10 == 3)
return 1 + countThrees(x / 10);
return countThrees(x / 10);
}
【问题讨论】:
标签: recursion