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.
- Convert the integer N to a string.
- Store each digit in a list.
- Sort the list in descending order.
- 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.