在 JavaScript 中按二进制中 1 位的数量对整数进行排序
我们需要编写一个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 ]
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短