题目描述
给你一个整数数组 arr 。请你将数组中的元素按照其二进制表示中数字 1 的数目升序排序。如果存在多个数字二进制中 1 的数目相同,则必须将它们按照数值大小升序排列。请你返回排序后的数组。
输入格式:
按照控制台提示依次输入,数组大小n,和n个数组中存放的元素
输入样例:
9
0 1 2 3 4 5 6 7 8
输出样例:
排序后的数组为: 0 1 2 4 8 3 5 6 7
代码:
#include <stdio.h>
#include <stdlib.h>
// 计算一个整数的二进制表示中数字 1 的数量
int countBits(int num) {
//请在此处开始编写你的代码
int count=0;
while(num>0){
count+=num&1;
num>>=1;
}
return count;
}
// 比较两个整数的二进制表示中数字 1 的数目和数值大小
int compare(const void* a, const void* b) {
//请在此处开始编写你的代码
int numA=*(const int*)a;
int numB=*(const int *)b;
int countA=countBits(numA);
int countB=countBits(numB);
if(countA==countB)
{
return numA-numB;
}
return countA-countB;
}
// 对整数数组按照二进制表示中数字 1 的数目和数值大小进行排序
void sortByBits(int arr[], int size) {
//请在此处开始编写你的代码
qsort(arr,size,sizeof(int),compare);
}
int main() {
int size;
// 从键盘输入数组大小
printf("请输入数组大小: ");
scanf("%d", &size);
int arr[size];
// 从键盘输入数组元素
printf("情输入数组元素: ", size);
for (int i = 0; i < size; ++i) {
scanf("%d", &arr[i]);
}
// 调用函数对数组按照二进制表示中数字 1 的数目和数值大小进行排序
sortByBits(arr, size);
// 输出排序后的数组
printf("排序后的数组为: ");
for (int i = 0; i < size; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}