【问题标题】:Given a sequence of integers, return the sum of all the integers that have an even index, multiplied by the integer at the last index给定一个整数序列,返回所有具有偶数索引的整数之和,乘以最后一个索引处的整数
【发布时间】:2021-06-15 20:24:57
【问题描述】:

这是我的解决方案,它通过了一些测试,但不是全部。谁能帮助我并解释原因?谢谢你:)

function evenLast(numbers) {
  let sum = 0;
  let lastNum = numbers.pop();
  let arr = numbers.filter(el => el % 2 === 0);

  
  for(let i = 0; i < arr.length; i++) {
    sum += (arr[i] * lastNum);
  } 
  return sum;
}

【问题讨论】:

  • 如果你弹出的最后一个数字是偶数索引处的整数怎么办?请记住,numbers.pop() 会变异 numbers。此外,您正在检查答案中@Nina 突出显示的值而不是索引。
  • 谢谢!我会尝试不同的方法。
  • 取决于最后一个索引是否为偶数,相乘前应包含在总和中。

标签: javascript arrays sum integer numbers


【解决方案1】:

你需要检查索引,而不是值

let arr = numbers.filter((_, i) => i % 2 === 0);

你可以在最后一步乘以总和。

for (let i = 0; i < arr.length; i++) {
    sum += arr[i]);
} 
return sum * lastNum;

更好的方法只需要一个循环,并通过增加 2 来对值求和。

function evenLast(numbers) {
    let sum = 0;

    for (let i = 0; i < numbers.length; i += 2) sum += numbers[i];

    return sum * numbers[numbers.length - 1];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多