#include #include #include using namespace std; struct node { int x;//数值 int cnt;//1的个数 }p[100005]; int n; int calc(int x)//计算x的二进制表示中1的个数 { int res=0; while(x) { if(x&1) res++; x>>=1; } return res; } bool cmp(const node& a,const node& b) { if(a.cnt==b.cnt) return a.x<b.x;//1的个数相同,按数值从小到大排序 return a.cnt<b.cnt;//按1的个数从小到大排序 } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&p[i].x); p[i].cnt=calc(p[i].x);//计算1的个数 } sort(p+1,p+n+1,cmp);//排序 for(int i=1;i<=n;i++) printf("%d ",p[i].x);//输出结果 return 0;

读入n个正整数按照十进制表示中1的个数从小到大排序 1的个数相同的按照从小到大排序c++代码

原文地址: https://www.cveoy.top/t/topic/gvtR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录