以下方法计算什么?假设最初使用 i = 0 调用该方法
public int mysteryMethod(String a, char b, int i) {
if (i == a.length())
return 0;
else if (b == a.charAt(i))
return mysteryMethod(a, b, i + 1) + 1;
else
return mysteryMethod(a, b, i + 1);
}
我对递归感到困惑。在第二个返回语句中,+1 在做什么。
最佳答案
在第二个 if 语句中,+1 正在计数。所以这里有一个提示。
What is the +1 counting?
在此处停止阅读并继续尝试。然后继续阅读下一个提示。
要回答上述问题,您应该查看 +1 发生的条件。这是当 b
等于 a.charAt(i)
时。
So what does this mean with respect to counting?
在此处停止阅读并继续尝试。继续阅读寻找答案。
该函数正在计算 b
在字符串 a
中出现的次数。在每次迭代中,它检查迭代 (ith) 位置是否等于 b
。如果是这样,将计数增加一个并从下一个位置开始重复该功能。否则,继续并检查下一次迭代。
关于java - 学习递归Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33745155/