用递归实现一个阶乘算法 5! = 5 * 4 * 3 * 2 * 1 = 120 用递归 function factorial(n) { if (n === 0) { return 1; } else { return n * factorial(n - 1); } }
用栈操作 function fact(n) { var s = new Stack(); while (n > 1) { //[5,4,3,2] s.push(n--); } var product = 1; while (s.length() > 0) { product *= s.pop(); } return product; } fact(5) //120