我的findOutlier函数有什么问题?为什么我会收到错误?

时间:2018-04-28 10:15:32

标签: javascript

您将获得一个包含整数的数组(其长度至少为3,但可能非常大)。该数组要么完全由奇数整数组成,要么完全由偶数整数组成,除了单个整数N.写一个方法,将数组作为参数并返回这个"异常值" Ñ

示例:[2,4,0,100,4,11,2602,36] 应该返回:11(唯一的奇数)

我的溶胶:

function findOutlier(integers){
var odd = false;
var even = false;
if ((integers[0]%2===0) && (integers[1]%2===0)) || ((integers[1]%2===0) && (integers[2]%2===0)){
    even = true;
}else{
    odd = true;
}

 if (odd){
    for (var i = 0; i < integers.length; i++){
        if (integers[i]%2 === 0){
            return integers[i];
    }}
}else if (even){
    for (var i = 0; i < integers.length; i++){
        if (integers[i]%2 !== 0){
            return integers[i];
 }}
}
}

1 个答案:

答案 0 :(得分:0)

您的第一个if条件需要用括号括起来: if a || b需要if (a || b)。然后它工作。 :)

&#13;
&#13;
function findOutlier(integers) {
  var odd = false;
  var even = false;
  if (((integers[0] % 2 === 0) && (integers[1] % 2 === 0)) || ((integers[1] % 2 === 0) && (integers[2] % 2 === 0))) {
    even = true;
  } else {
    odd = true;
  }

  if (odd) {
    for (var i = 0; i < integers.length; i++) {
      if (integers[i] % 2 === 0) {
        return integers[i];
      }
    }
  } else if (even) {
    for (var i = 0; i < integers.length; i++) {
      if (integers[i] % 2 !== 0) {
        return integers[i];
      }
    }
  }
}

var result = findOutlier([2, 4, 0, 100, 4, 11, 2602, 36] );
console.log(result);
&#13;
&#13;
&#13;

这是解决这个问题的另一种方法:

&#13;
&#13;
function findOutlier(integers) {
  var outlier;
  var odd = [];
  var even = [];
  
  // Push odd numbers to odd array and even numbers to even array.
  integers.forEach(function(element) {
    if (element % 2 == 0) even.push(element);
    else odd.push(element);
  });

  // Ensure that the input is valid.
  if (odd.length != 1 && even.length != 1) {
    console.log("There is no single outlier! The array contains " + odd.length + " odd integers and " + even.length + " even integers.")
  } else {
    // Get outlier.
    outlier = (odd.length == 1 ? odd[0] : even[0]);
  }
  
  return outlier;
}

var result = findOutlier([2, 4, 0, 100, 4, 11, 2602, 36]);
console.log(result);
&#13;
&#13;
&#13;