N次一个数字使用递归_how递归方法的返回类型工作

huangapple go评论67阅读模式
英文:

N times of a number using Recursion_how return type of recursion method works

问题

private static int nTimesK(int n, int k) {
    System.out.println("n: " + n);
    // 递归情况
    if(n > 1) { 
        return k + nTimesK(n - 1, k);
    }
    // 基本情况 n = 1
    else { 
        return k;
    }
}
public static void main(String[] args) {
    int result = nTimesK(4, 4);
    System.out.println("Result: " + result);
}

查询:
它运行如下:return k + nTimesK(3, 4),它运行如下:return k + nTimesK(2, 4),它运行如下:return k + nTimesK(1, 4)
其中 n=1 是基本情况。想要知道如何得到 4+nTimesK(3, 4) 会得出值为 8,接着是 12,最后是 16。

英文:
private static int nTimesK(int n, int k) {
System.out.println("n: " + n);
// Recursive Case
if(n > 1) { 
    return k + nTimesK(n - 1, k);
}
// Base Case n = 1
else { 
    return k;
}
}
public static void main(String[] args) {
int result = nTimesK(4, 4);
System.out.println("Result: " + result);
}

Query:
it runs like return k+ntimesK(3,4),it runs like return k+ntimesK(2,4),it runs like return k+ntimesK(1,4)
where n=1 is the base case. wanted to know how 4+ntimesK(3,4) will result in value 8 followed by 12 and finally 16.

答案1

得分: 1

假设你调用这个方法并传入4和4(即nTimesK(4,4)),在方法内部,因为n大于1(4大于1),它执行return k + nTimes(n-1, k)。该语句被替换为4 + nTimesK(3,4)(我们称这个点为A)。计算不能返回响应,因为它必须等待nTimesK(3,4)的结果。当调用nTimesK(3,4)时,它应该返回4 + nTimesK(2,4)(我们称这个点为B)给第一个调用(A)。它必须等待nTimesK(2,4)在返回结果之前执行。因此,调用nTimesK(2,4),它返回4 + nTimesK(1,4)(我们称这个点为C)。当C执行nTimesK(1,4)时,调用返回4(作为基本条件,即n = 1)。所以,C现在可以返回4 + 4(=8)给B。B现在也可以返回4 + 8(=12)给A。A计算4 + 12(=16),并将答案返回给最初的调用。因此得到值16。

英文:

Assume you call the method passing in 4 and 4 (i.e. nTimesK(4,4)), inside the method, since n>1 (4 is greater than 1) it executes return k + nTimes(n-1, k). The statement is replaced by 4 + nTimesK(3,4) (we call this point A). The computation can not return the response because it has to wait for the result of nTimesK(3,4). When nTimesK(3,4) is called, it should return 4 + nTimesK(2,4)(we call this point B) to the first call (A). It has to wait for nTimesK(2,4) to execute before returning the result. So, nTimesK(2,4) is called and it returns 4 + nTimesK(1,4) (we call this point C). When C executes nTimesK(1,4), the call returns 4 (being the base condition. ie. n = 1). So, C can now return 4 + 4 (=8)to B. B can also now return 4 + 8 (=12) to A. A computes 4 + 12 (=16) and returns the answer to the original call. Hence the value 16.

huangapple
  • 本文由 发表于 2020年8月18日 10:42:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63461118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定