使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP