Sort Integers by The Number of 1 Bits

Given an array of integers, sort the numbers by the number of set bits in their binary representation, and break ties by numeric value. This problem is bounded because the bit-count range is small.

Input Format

arr = array of non-negative integers

Output Format

array sorted by number of set bits, then by value

Constraints

  • 1 <= arr.length <= 500; 0 <= arr[i] <= 10^4

Examples

Example 1:

Input:

arr = [0,1,2,3,4,5,6,7,8]

Output:

[0,1,2,4,8,3,5,6,7]

Explanation:

Numbers are ordered by bit count, then by value.

Example 2:

Input:

arr = [1024,512,256,128]

Output:

[128,256,512,1024]

Explanation:

All values have one set bit, so they are ordered numerically.

Loading...
Sort Integers by The Number of 1 Bits