All problems

Problem 569

Sort Integers by the Number of 1 Bits

Easy · 10 pts · Array, Sorting, Bit Manipulation

Problem

Sort the array by the number of 1 bits in the binary form of each value, from fewest to most. Values with the same number of 1 bits are sorted by their value in increasing order. For example, 7 = 111 has three 1 bits and 8 = 1000 has one, so 8 comes before 7. Count the bits of each value once and sort with a two-part key.

Input

The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].

Output

Print the sorted array, space-separated.

Constraints

1 <= N <= 100000; 0 <= A[i] <= 10000

Example input

9
0 1 2 3 4 5 6 7 8

Example output

0 1 2 4 8 3 5 6 7

Explanation

For 0 1 2 3 4 5 6 7 8: 0 has no 1 bits, then 1 2 4 8 have one, 3 5 6 have two, and 7 has three. So the result is 0 1 2 4 8 3 5 6 7.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Kth Smallest Number in a Multiplication Table Next: Sort the Matrix Diagonally