MICROSOFT Coding Question β Solved
The binary cardinality of a number is the count of 1's in its binary representation. For example, the decimal number 10 corresponds to the binary number 1010, which has a binary cardinality of 2 because it contains two 1's. Given an array of decimal integers, sort it by: 1. Increasing binary cardinality (primary criterion) 2. Increasing decimal value (secondary criterion, when cardinalities are equal) Return the sorted array.
Example n=4 nums = [1, 2, 3, 4] 110 β 12, so 1's binary cardinality is 1. 210 β 102, so 2's binary cardinality is 1. 310 β 112, so 3's binary cardinality is 2. 410 β 1002, so 4's binary cardinality is 1. The sorted elements with binary cardinality of 1 are [1, 2, 4]. The array to return is [1, 2, 4, 3].
Function Description: Complete the function cardinalitySort in the editor with the following parameter(s): int nums[n]: an array of decimal integers Returns int[n]: the integer array nums sorted ascending, by binary cardinality, then by decimal value for ties.
Constraints: 1 β€ n β€ 10^5, 1 β€ nums[i] β€ 10^6
STDIN Input Format for Custom Testing: Sample Case 0
Sample Input 0: nums size n = 5 nums = [31, 15, 7, 3, 2] Sample Output 0: [2, 3, 7, 15, 31]
Explanation 0: 3110 β 11111 so its binary cardinality is 5. 1510 β 1111 so its binary cardinality is 4. 710 β 111 so its binary cardinality is 3. 310 β 11 so its binary cardinality is 2. 210 β 10 so its binary cardinality is 1. Sort the array by ascending binary cardinality and then by ascending decimal value: nums sorted = [2, 3, 7, 15, 31].
Sample Case 1: Sample Input 1: nums size n = 1 nums = [3] Sample Output 1: [3]
Explanation 1: The binary cardinality of 310 β 11 is 2. The function returns nums sorted = [3].
Asked in:
MICROSOFT