You are given an array of integers, and you have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order. Here is one example, array [ 5, 0, 7, 1, 2, 6, 3, 4, 8 ] would result to [ 0, 1, 2, 4, 8, 3, 5, 6, 7 ] since, [ 0 ] is the only integer with 0 bits, [ 1, 2, 4, 8 ] all have 1 bit, [ 3, 5, 6] have 2 bits and [ 7 ] has 3 bits. So, the sorted array by bits is [ 0, 1, 2, 4, 8, 3, 5, 6, 7 ]. Another example, array [ 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1 ] would result to [ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 ]. For more details,
here is the link to the leetcode question.
One way to solve this problem is by using the custom comparer to sort the array. This approach needs no extra modules to sort the array (like Linq). A common method is defined to convert the decimal number to binary number and then count the number of 1's from that binary number. We used the System.Convert.ToString() to convert the decimal to binary rather then just dividing it by 2s. After counting the number of 1's in the binary representation of each integer, we will sort them by the number of 1's ascending and if two numbers have same 1's then we will compare by the value. Here is the C# code for the algorithm,