根據二進位制中 1 的數量對 JavaScript 中的整數進行排序
我們需要編寫一個 JavaScript 函式,它接收一個整數陣列作為唯一引數。
這個函式應該根據二進位制表示中存在的 1 的數量對陣列中存在的整數進行遞增排序。如果兩個或更多數字在它們的二進位制中具有相同數量的 1,那麼它們應該根據它們的大小按遞增順序排序。
例如 -
如果輸入陣列是 -
const arr = [34, 37, 23, 89, 12, 31, 23, 89];
那麼輸出陣列將是 -
const output = [34, 12, 37, 23, 89, 23, 89, 31];
示例
以下是程式碼 -
const arr = [34, 37, 23, 89, 12, 31, 23, 89]; const sortByBinary = (arr = []) => { const calculateOne = (str = '') => { let res = 0; for(let i = 0; i < str.length; i++){ if(str[i] === '1'){ res++; }; }; return res; } const sorter = (a, b) => { const firstCount = calculateOne((a >>> 0).toString(2)); const secondCount = calculateOne((b >>> 0).toString(2)); return firstCount - secondCount; }; arr.sort(sorter); }; sortByBinary(arr); console.log(arr);
輸出
以下是控制檯輸出 -
[ 34, 12, 37, 23, 89, 23, 89, 31 ]
廣告