在 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 ]
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下