-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursion.js
More file actions
40 lines (37 loc) · 845 Bytes
/
Copy pathrecursion.js
File metadata and controls
40 lines (37 loc) · 845 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// recursion practice
// factorial, given number return num * (num - 1)... *3 * 2 *1
// no recursion
let facAnswer = 1;
const fac = num => {
while (num !== 0) {
facAnswer *= num;
num -= 1;
}
};
fac(5);
console.log('facAnswer', facAnswer);
// with recursion
// factorial = num * (factorial (num - 1))
const recurFac = num => {
if (num === 1) return 1;
return num * recurFac(num - 1);
};
const recurFacRes = recurFac(5);
console.log('recurFacRes', recurFacRes);
// sorted list problem
function recur(l1, l2, ls) {
console.log('l2', l2.next);
console.log('l1', l1.next);
let newl1 = l1;
let newl2 = l2;
if (!l1.next || !l2.next) return ls;
if (l1.val >= l2.val) {
ls.push(l1.val);
newl1 = l1.next;
}
if (l2.val > l1.val) {
ls.push(l2.val);
newl2 = l2.next;
}
return recur(newl1, newl2, ls);
}