Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created February 25, 2026 18:23
Show Gist options
  • Select an option

  • Save tatsuyax25/648306df9fb65913c39bd73f808d399a to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/648306df9fb65913c39bd73f808d399a to your computer and use it in GitHub Desktop.
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. Retur
/**
* @param {number[]} arr
* @return {number[]}
*/
var sortByBits = function(arr) {
// Helper: count how many 1-bits are in the binary representation
function bitCount(n) {
// Convert to binary string and count '1' characters
return n.toString(2).split('1').length - 1;
}
// Sort using a custom comparator
return arr.sort((a, b) => {
const bitsA = bitCount(a);
const bitsB = bitCount(b);
// Primary sort: by number of 1-bits
if (bitsA !== bitsB) {
return bitsA - bitsB;
}
// Secondary sort: numeric value
return a - b;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment