📜  门| GATE CS 2018 |问题 21(1)

📅  最后修改于: 2023-12-03 15:28:38.171000             🧑  作者: Mango

GATE CS 2018 Question 21

This is a question from the Computer Science GATE exam 2018 which involves solving a programming problem. In this question, you are given an array of integers and are required to sort the array in non-descending order, based on the number of 1's in the binary representation of each element.

Problem Statement

Given an array of integers A of size n, sort the array in non-descending order, based on the number of 1's in the binary representation of each element. If two or more elements have the same number of 1's in their binary representation, then sort them in non-descending order of their integer values.

Input:

The first line of the input contains an integer n indicating the size of the array. The second line of the input contains the n integers of the array A.

Output:

Output the sorted array in a single line, separated by space.

Constraints:

  • 1 ≤ n ≤ 10^3
  • 1 ≤ A[i] ≤ 10^9
Approach

To solve this problem, we have to first calculate the number of 1's in the binary representation of each element in the array. We can do this using the bin() function in Python which returns the binary representation of a number as a string.

After we have calculated the number of 1's in the binary representation of each element, we can use the sorted() function in Python to sort the array first by the number of 1's and then by the integer values.

Solution
def count_ones(n):
    # Function to count the number of 1's in the binary representation of a number
    return bin(n).count('1')

n = int(input())
A = list(map(int, input().split()))

A = sorted(A, key=lambda x: (count_ones(x), x))

print(*A)

The above Python code calculates the number of 1's in the binary representation of each element using the count_ones() function and sorts the array A by the number of 1's and then by the integer values using the sorted() function and the key argument.

Conclusion

In this article, we solved the programming problem from the GATE CS 2018 exam and provided a detailed explanation of the problem, approach, and solution in Python.