使用 JavaScript 查詢在陣列中沒有匹配的正數或負數的陣列數字


問題

我們要求編寫一個 Javascript 函式,該函式接收一個整數陣列。對於陣列中的每個數字,陣列中還將存在其負數或正數的互補數,但對於恰好一個數字,將不存在互補數。

我們的函式應從陣列中查詢並返回該數字。

示例

以下是程式碼 -

 即時演示

const arr = [1, -1, 2, -2, 3];
const findOddNumber = (arr = []) => {
   let count = 0;
   let number = arr.reduce((total, num) => {
      if (num >= 0)
         count++
      else
         count--
      return total + num;
   }, 0)
   return number / Math.abs(count);
};
console.log(findOddNumber(arr));

輸出

3

更新於:20-4-2021

136 次瀏覽

開啟你的 職業 生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.