class Solution {
public:
struct cmp{
bool operator()(const int &x,const int &y)
{
if(__builtin_popcount(x)>__builtin_popcount(y))
{
return true;
}
if(__builtin_popcount(x)==__builtin_popcount(y))
{
if(x>y)
{
return true;
}
else
{
return false;
}
}
return false;
}
};
vector<int> sortByBits(vector<int>& arr) {
//用_builtin_popcount()函数计算每一个数字的二进制形式中1的个数
sort(arr.begin(),arr.end(),cmp());
reverse(arr.begin(),arr.end());
return arr;
}
};
LeetCode:1356. 根据数字二进制下 1 的数目排序
最新推荐文章于 2025-08-25 12:47:46 发布
本文介绍了一种基于二进制位计数的排序算法实现,通过使用__builtin_popcount()函数计算整数中1的个数,并自定义比较函数对数组进行排序。最后,算法将排序后的数组逆序输出。
329

被折叠的 条评论
为什么被折叠?



