bool custom_compare(int a, int b)
{
int binary_count_a =0,binary_count_b=0,a_mid=a,b_mid=b;
while(a) {binary_count_a ++;a &=a-1;}
while(b) {binary_count_b ++;b &=b-1;}
if(binary_count_a<binary_count_b) return true;
else if(binary_count_a>binary_count_b)return false;
else if((binary_count_a==binary_count_b)&&(a_mid<b_mid)) return true;
else return false;
}
class Solution {
public:
vector<int> sortByBits(vector<int>& arr) {
if(arr.size()<2) return arr;
sort(arr.begin(),arr.end(),custom_compare);
return arr;
}
};
1356. 根据数字二进制下 1 的数目排序 - 力扣(LeetCode) (leetcode-cn.com)
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
// int count_binary_one(int n)
// {
// int count = 0;
// while(n != 0) {
// count += n & 1;
// n >>= 1;
// }
// return count;
// };
int count_binary_one(int n)
{
int count = 0;
while(n) {
count ++;
n &=n-1;
}
return count;
}
bool custom_compare(int a, int b)
{
int binary_count_a =0,binary_count_b=0;
while(a) {binary_count_a ++;a &=a-1;}
while(b) {binary_count_b ++;b &=b-1;}
if(binary_count_a<binary_count_b) return true;
else return false;
}
int main(){
vector<int> arr{0,1,2,3,4,5,6,7,8};
sort(arr.begin(), arr.end(), custom_compare);
for(int a:arr) cout<<a<<" ";
cout<<endl<<(arr.back()>>1)<<" "<<arr.back();//z注意移位只是个操作,变量不变赋值之后才变
}
0 1 2 4 8 3 5 6 7
3 7