根据数字二进制下 1 的数目排序
给你一个整数数组 arr 。请你将数组中的元素按照其二进制表示中数字 1 的数目升序排序。
如果存在多个数字二进制中 1 的数目相同,则必须将它们按照数值大小升序排列。
请你返回排序后的数组。
class Solution {
public:
struct cmp {
int Bytr1Size(int num) {
int count = 0;
while(num) {
count++;
num = num & (num - 1);
}
return count;
}
bool operator() (int A, int B) {
int sum1 = Bytr1Size(A);
int sum2 = Bytr1Size(B);
if(sum1 != sum2) { return sum1 < sum2 ? true : false; }
return A < B ? true : false;
}
};
vector<int> sortByBits(vector<int>& arr) {
if(arr. size() == 0) { return vector<int>(); }
cmp cm;
sort(arr.begin(), arr.end(), cm);
return arr;
}
};