按 C++ 中 set 位的计数对数组进行排序
在这里,我们将看到一个根据 set 位对数组进行排序的有趣问题。当数组中的某个元素具有更高的 set 位数时,它将位于另一个具有较低 set 位数的元素之前。假设一些数字为 12、15、7。因此,set 位基本上是它们在二进制表示中的 1 的数量。它们分别为 1100 (12)、1111 (15) 和 0111 (7)。因此,排序后的结果如下所示 -
1111, 0111, 1100 (15, 7, 12)
首先,我们必须找到 set 位数。然后,我们使用 C++ STL 排序函数对它们进行排序。我们必须根据 set 位数创建比较逻辑
算法
getSetBitCount(number): Begin count := 0 while number is not 0, do if number AND 1 = 1, then increase count by 1 number = right shift number by one bit done return count End compare(num1, num2): Begin count1 = getSetBitCount(num1) count2 = getSetBitCount(num2) if count1 <= count2, then return false, otherwise return true End
示例
#include<iostream>
#include<algorithm>
using namespace std;
int getSetBitCount(int number){
int count = 0;
while(number){
if(number & 1 == 1)
count++;
number = number >> 1 ; //right shift the number by one bit
}
return count;
}
int compare(int num1, int num2){
int count1 = getSetBitCount(num1);
int count2 = getSetBitCount(num2);
if(count1 <= count2)
return 0;
return 1;
}
main(){
int data[] = {2, 9, 4, 3, 5, 7, 15, 6, 8};
int n = sizeof(data)/sizeof(data[0]);
sort(data, data + n, compare);
for(int i = 0; i<n; i++){
cout << data[i] << " ";
}
}输出
15 7 9 3 5 6 2 4 8
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP