Find The Parity Outlier

  • Find The Parity Outlier
    • javascript filter練習
  • 考慮
    • 陣列的總個數會影響加總最後是奇數還是偶數的結果
      • 偶數個奇數相加會變成偶數
  • 測試
    • 針對奇數個數的情況進行確認
    • 測試順序互換是否影響最後的結果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function findOutlier(integers){
let evenNum = 0, oddNum = 0;
for(let i=0; i<integers.length;i++) {
if(integers[i] % 2 == 0) {
evenNum++;
} else {
oddNum++;
}
}
return integers.filter(val => {
val = val < 0 ? -val : val
return (val % 2==0 && evenNum == 1) ||
(val % 2==1 && oddNum == 1)
})[0]
}

1
2
3
4
5
6
Test.assertEquals(findOutlier([ 0, 2 ,-1]), -1)
Test.assertEquals(findOutlier([1, 2, 3]), 2)
Test.assertEquals(findOutlier([2,6,8,10,3]), 3)
Test.assertEquals(findOutlier([0,0,3,0,0]), 3)
Test.assertEquals(findOutlier([1,1,1,0,1,7,7,1]), 0)
Test.assertEquals(findOutlier([17,6,8,10,6,12,24,36]),17)