用递归代替循环

119 阅读1分钟

谁能告诉我或指导我对这个问题的正确解释?我对编码非常陌生,我想了解如何解决这个问题。


function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n - 1];
}
// Only change code above this line
}

// sum([2,3,4,5],3)
// sum([2,3,4,5], 3-1 = 2] + arr[3-1 = 2])
// sum(2+3) -- sum of first 2 values = (5) + arr[2] (2nd index of arr is 4))
// so: 5 + 4 = 9

// sum([2,3,4], 1)
// sum([2,3,4],1-1 = 0)(since it is 0, it returns 0) + arr[1-1 = 0])
// arr[0] is 2 because it is the zereoth index of arr
// so: 0 + 2 = 2)
  **Your browser information:**

用户代理是。Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15

挑战。 使用递归替换循环

挑战赛的链接。

freecodecamp.org

freeCodeCamp.org

学习代码--免费的

3个帖子 - 2个参与者

阅读完整主题