A datacenter technician receives a batch of diagnostic codes pulled from server racks. Each diagnostic code is a non-negative integer, and its binary representation lights up a bank of status indicators — one lit indicator for every 1 bit in the code. To decide which racks deserve attention first, the technician wants the codes reordered so that codes lighting up fewer indicators come first. Among codes that light up the same number of indicators, the smaller numeric code should come first.
Given the batch of diagnostic codes, output them rearranged into this inspection order.
Line 1: a single integer n, the number of diagnostic codes. Line 2: n space-separated non-negative integers, the diagnostic codes, in the order they were pulled (duplicates may occur).
A single line containing the n diagnostic codes, space-separated, reordered so that codes with fewer set bits come first, ties broken by ascending numeric value.
1 <= n <= 1000 0 <= each diagnostic code <= 100000
Example 1
Input
8 0 1 2 3 4 5 6 7
Expected
0 1 2 4 3 5 6 7
Explanation
Set-bit counts: 0->0, 1->1, 2->1, 3->2, 4->1, 5->2, 6->2, 7->3. Grouping by count and sorting each group by value: count 0 gives [0]; count 1 gives [1, 2, 4]; count 2 gives [3, 5, 6]; count 3 gives [7]. Concatenating gives 0 1 2 4 3 5 6 7.
Example 2
Input
5 1024 512 256 128 1023
Expected
128 256 512 1024 1023
Explanation
128, 256, 512, and 1024 are all powers of two, so each has exactly one set bit; sorted ascending among themselves they are 128, 256, 512, 1024. 1023 equals 2^10 - 1, whose binary form is ten 1 bits, so it has the most set bits and comes last: 128 256 512 1024 1023.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →