8000 Add alternative solution in fibonacci-solution.js · amcollie/javascript-exercises@123e00d · GitHub
[go: up one dir, main page]

Skip to content

Commit 123e00d

Browse files
authored
Add alternative solution in fibonacci-solution.js
1 parent 908c4ed commit 123e00d

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed
Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,25 @@
11
const fibonacci = function(count) {
22
if (count < 0) return "OOPS";
33
if (count === 0) return 0;
4-
5-
const fib = [0, 1];
4+
5+
let firstPrev = 1;
6+
let secondPrev = 0;
7+
68
for (let i = 2; i <= count; i++) {
7-
fib[i] = fib[i - 1] + fib[i - 2];
9+
let current = firstPrev + secondPrev;
10+
secondPrev = firstPrev;
11+
firstPrev = current;
812
}
9-
return fib[count];
13+
14+
return firstPrev;
15+
1016
};
1117

18+
// Another way to do it is by using an iterative approach with an array containing two values, 0 and 1.
19+
// const fib = [0, 1];
20+
// for (let i = 2; i <= count; i++) {
21+
// fib[i] = fib[i - 1] + fib[i - 2];
22+
// }
23+
// return fib[count];
24+
1225
module.exports = fibonacci;

0 commit comments

Comments
 (0)
0