C# Coding Test Course, Sorting Digits in Descending Order

Enhance your problem-solving skills for coding test preparation.

Problem Description

Write a function that takes a given integer N and returns a new integer formed by sorting its digits in descending order.

Input Conditions

  • An integer N is given, which is between 0 and 1 billion (inclusive).

Output Conditions

  • Return an integer formed by sorting the digits of integer N in descending order.

Example

Input Example

N = 118372

Output Example

873211

Approach to the Problem

The following steps are needed to solve this problem.

  1. Convert the integer N to a string.
  2. Store each digit in a list.
  3. Sort the list in descending order.
  4. Combine the sorted list elements back into a string and convert it to an integer.

C# Code Implementation

Below is the C# code to solve the given problem.

            
                using System;
                using System.Linq;

                public class Program
                {
                    public static void Main(string[] args)
                    {
                        int N = 118372;
                        Console.WriteLine(SortDigitsDescending(N));
                    }

                    public static int SortDigitsDescending(int n)
                    {
                        // Convert the integer to a string
                        var digits = n.ToString().ToCharArray();

                        // Sort the string in descending order
                        Array.Sort(digits);
                        Array.Reverse(digits);

                        // Convert the sorted string back to an integer
                        return int.Parse(new string(digits));
                    }
                }
            
        

Code Explanation

I will explain each step used in the above code.

1. Convert the integer to a string

n.ToString().ToCharArray() is used to convert the integer to a string. Then, using the ToCharArray() method, each digit is converted to a character array.

2. Sort the digits

Array.Sort(digits) is called to sort the digits in ascending order. Then, Array.Reverse(digits) is called to change it to descending order.

3. Convert to an integer

Finally, new string(digits) converts the character array to a string, and int.Parse is used to convert it to an integer.

Time Complexity

The time complexity of this algorithm is O(d log d), where d is the number of digits in the input integer. The time taken to sort the digits is O(d log d), while other operations take O(d).

Conclusion

In this course, we learned how to sort a given integer in descending order. We effectively solved this problem using basic array manipulation and string conversion in C#. Although it is a fundamental algorithm problem, it can evolve into various application problems, so practicing more problems is essential.

© 2023 C# Coding Test Course. All rights reserved.