[LeetCode] Sort Integers by The Number of 1 Bits

1356. Sort Integers by The Number of 1 Bits

You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1’s in their binary representation and in case of two or more integers have the same number of 1’s you have to sort them in ascending order.

Return the array after sorting it.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
vector<int> sortByBits(vector<int>& arr) {
auto compare = [](int a, int b) {
int bpca = __builtin_popcount(a);
int bpcb = __builtin_popcount(b);
return bpca == bpcb ? a < b : bpca < bpcb;
};
sort(arr.begin(), arr.end(), compare);
return arr;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/07/PS/LeetCode/sort-integers-by-the-number-of-1-bits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.