Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Sắp xếp số nguyên theo số bit 1 trong nhị phân JavaScript

Viết hàm sắp xếp mảng số nguyên tăng dần theo số bit 1 trong biểu diễn nhị phân. Nếu số bit 1 bằng nhau, sắp theo giá trị tăng dần.

Ví dụ: [34,37,23,89,12,31,23,89] → [34,12,37,23,89,23,89,31].

Ví dụ

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 || a - b;
  };
  arr.sort(sorter);
};
sortByBinary(arr);
console.log(arr);

Kết quả

[34, 12, 37, 23, 89, 23, 89, 31]