* Fix code not passing on challenge tests The code was not passing the challenge tests because we must sum only odd numbers. Cince we didn't provided an initial value for reduce, it would use the first element of the array, and if it was an odd number, it would skip our validation and add it to the final result. [https://www.freecodecamp.org/forum/t/sum-all-odd-fibonacci-numbers-solution-not-passing-all-tests/236058](https://www.freecodecamp.org/forum/t/sum-all-odd-fibonacci-numbers-solution-not-passing-all-tests/236058) * Same English fixed for Arabic * Same English fix for Chinese * Same English fix for Portuguese * Same English fix for Russian * Same English fix for Spanish
5.6 KiB
5.6 KiB
title, localeTitle
title | localeTitle |
---|---|
Sum All Odd Fibonacci Numbers | 求所有奇数斐波纳契数 |
如果卡住,请记得使用**
Read-Search-Ask
** 。尝试配对程序并编写自己的代码
问题说明:
您将需要收集所有Fibonacci数字,然后检查奇数。一旦你得到奇怪的,那么你将把它们全部添加。最后一个数字应该是作为参数给出的数字,如果它实际上恰好是一个偏离的斐波纳契数。
相关链接
提示:1
要获得系列的下一个数字,您需要将当前的数字添加到前一个系列,这将为您提供下一个系列。
现在尝试解决问题
提示:2
要检查数字是否均匀,您需要检查的是number % 2 == 0
。
现在尝试解决问题
提示:3
当你得到下一个奇怪的那个时,不要忘记将它添加到一个可以在最后返回的全局变量。 result += currNumber;
会做的伎俩。
现在尝试解决问题
扰流警报!
提前解决!
基本代码解决方案
function sumFibs(num) {
var prevNumber = 0;
var currNumber = 1;
var result = 0;
while (currNumber <= num) {
if (currNumber % 2 !== 0) {
result += currNumber;
}
currNumber += prevNumber;
prevNumber = currNumber - prevNumber;
}
return result;
}
// test here
sumFibs(4);
代码说明:
- 创建一个变量以记录当前和之前的数字以及将返回的结果。
- 使用while循环确保我们不会超过作为参数给出的数字。
- 我们使用模运算来检查当前数字是奇数还是偶数。如果是偶数,请将其添加到结果中。
- 通过旋转获取下一个数字并在之后交换值来完成斐波纳契圆。
- 返回结果。
相关链接
- JS while Loop
中级代码解决方案:
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);
}, 0);
}
// test here
sumFibs(4);
代码说明:
- 创建一个斐波纳契数列,直到num 。
- 使用
reduce()
方法查找数组奇数成员的总和。 - 归还总和。
相关链接
捐款说明:
请勿添加与任何现有解决方案类似的解决方案。如果您认为它**相似但更好** ,那么尝试合并(或替换)现有的类似解决方案。
- 添加解决方案的说明。
- 将解决方案分为以下类别之一 - 基本 , 中级和高级 。
- 如果您添加了任何**相关的主要内容,**请仅添加您的用户名。 (
不要 删除任何现有的用户名 )