https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers/


#1

Function sumFibs(num) {
// Perform checks for the validity of the input
if (num < 0) return -1;
if (num === 0 || num === 1) return 1;

// Create an array of fib numbers till num
const arrFib = [1, 1];
let nextFib = 0;

// We put the new Fibonacci numbers to the front so we
// don't need to calculate the length of the array on each
// iteration
while((nextFib = arrFib[0] + arrFib[1]) <= num) {
    arrFib.unshift(nextFib);
}

// Sum only the odd numbers and return the value
return arrFib.reduce((acc, curr) => {
    return acc + curr * (curr % 2);
}); 

}
// test here
sumFibs(4);
应该在reduec函数中加一个初始化的值,如果arr[0]是一个偶数就会被计算入result里面。
return arrFib.reduce((acc, curr) => {
return acc + curr * (curr % 2);
}, 0); 即可

浏览器信息

  • chrome 最新版:
  • 操作系统 win 8:

题目相关

https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers/