按 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