mirror of
https://github.com/10h30/odin-javascript-exercises.git
synced 2026-06-05 15:09:09 +09:00
Add alternative solution in fibonacci-solution.js
This commit is contained in:
@@ -2,11 +2,24 @@ const fibonacci = function(count) {
|
||||
if (count < 0) return "OOPS";
|
||||
if (count === 0) return 0;
|
||||
|
||||
const fib = [0, 1];
|
||||
let firstPrev = 1;
|
||||
let secondPrev = 0;
|
||||
|
||||
for (let i = 2; i <= count; i++) {
|
||||
fib[i] = fib[i - 1] + fib[i - 2];
|
||||
let current = firstPrev + secondPrev;
|
||||
secondPrev = firstPrev;
|
||||
firstPrev = current;
|
||||
}
|
||||
return fib[count];
|
||||
|
||||
return firstPrev;
|
||||
|
||||
};
|
||||
|
||||
// Another way to do it is by using an iterative approach with an array containing two values, 0 and 1.
|
||||
// const fib = [0, 1];
|
||||
// for (let i = 2; i <= count; i++) {
|
||||
// fib[i] = fib[i - 1] + fib[i - 2];
|
||||
// }
|
||||
// return fib[count];
|
||||
|
||||
module.exports = fibonacci;
|
||||
|
||||
Reference in New Issue
Block a user