LeetCode——Find 1+2+…+n

Title description

Problem-solving ideas

  1. Use recursion
  2. Using the reduce method of the array, the initial accumulator value is set to 1, and then the index subscript +1 is accumulated.

Problem-solving code

var sumNums = function (n) {
    
    
    return Array(n).fill(null).reduce((pre, item, idx) => pre + idx + 1, 0)
};

Achieve effect

Guess you like

Origin blog.csdn.net/sinat_41696687/article/details/114776762