Sort Integers by The Number of 1 Bits

Easy

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.

Examples

Input:arr = [0,1,2,3,4,5,6,7,8]
Output:[0,1,2,4,8,3,5,6,7]
Explanation:

Sorted by bit count then value.

Input:arr = [1024, 512, 256, 128, 64, 32, 16]
Output:[16, 32, 64, 128, 256, 512, 1024]
Explanation:

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.

Input:arr = [10, 100, 1000, 1]
Output:[1, 10, 100, 1000]
Explanation:

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

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!