Description
You are given an integer array arr. Sort the integers in ascending order by the number of 1's in their binary representation. For integers with the same number of 1's, sort them in ascending order. Return the result as an array.
Examples
arr = [0,1,2,3,4,5,6,7,8][0,1,2,4,8,3,5,6,7]Group by 1-bit count: {0,1,2,4,8} have 0-1 bits, {3,5,6} have 2 bits, {7} has 3 bits. Within groups, sort by value. Result: [0,1,2,4,8,3,5,6,7].
arr = [1024, 512, 256, 128, 64, 32, 16][16, 32, 64, 128, 256, 512, 1024]All numbers are powers of 2, so each has exactly one 1-bit in binary (16=10000, 32=100000, etc.). Since they all have the same number of 1's, they are sorted in ascending order by value.
arr = [10, 100, 1000, 1][1, 10, 100, 1000]Binary representations: 1=1 (1 bit), 10=1010 (2 bits), 100=1100100 (3 bits), 1000=1111101000 (6 bits). Each has different number of 1-bits, so sorting by bit count gives ascending order by value.
Constraints
- •
1 ≤ arr.length ≤ 500 - •
0 ≤ arr[i] ≤ 10^4