class Solution:
def sortByBits(self, arr):
return sorted(arr, key=lambda x: (bin(x).count('1'), x))
class Solution {
public:
vector<int> sortByBits(vector<int>& arr) {
sort(arr.begin(), arr.end(), [](int a, int b) {
int countA = __builtin_popcount(a);
int countB = __builtin_popcount(b);
if (countA == countB)
return a < b;
return countA < countB;
});
return arr;
}
};
class Solution {
public int[] sortByBits(int[] arr) {
Integer[] nums = new Integer[arr.length];
for (int i = 0; i < arr.length; i++) {
nums[i] = arr[i];
}
Arrays.sort(nums, (a, b) -> {
int countA = Integer.bitCount(a);
int countB = Integer.bitCount(b);
if (countA == countB) return a - b;
return countA - countB;
});
for (int i = 0; i < arr.length; i++) {
arr[i] = nums[i];
}
return arr;
}
}
var sortByBits = function(arr) {
return arr.sort((a, b) => {
const countA = a.toString(2).split('1').length - 1;
const countB = b.toString(2).split('1').length - 1;
if (countA === countB) return a - b;
return countA - countB;
});
};
arr. The task is to sort the array in ascending order, but with a twist: instead of sorting by the integer values directly, you must first sort the numbers by the number of 1 bits in their binary representation (also called their "Hamming weight"). If two numbers have the same number of 1 bits, they should be ordered by their value in ascending order.
arr is a non-negative integer.arr = [0,1,2,3,4,5,6,7,8][0,1,2,4,8,3,5,6,7]
3 (binary 11) has two 1-bits, while 4 (binary 100) has only one.
arr, compute the number of 1s in its binary representation. This is often called the Hamming weight or population count. Most languages offer a built-in or easy way to do this (e.g., bin(x).count('1') in Python, __builtin_popcount in C++).(bit_count, value) ensures the primary sort is by 1-bits, and the secondary sort is by the integer value.arr = [0,1,2,3,4,5,6,7,8] step by step:
0b0 → 00b1 → 10b10 → 10b11 → 20b100 → 10b101 → 20b110 → 20b111 → 30b1000 → 1[0, 1, 2, 4, 8, 3, 5, 6, 7]