Sort the digits programming exercise.
The winter is coming, and all the warehouses are nicely packed with food. But someone needs to sort it all. So the king offers a noble title to anyone who can:
Write a function that takes an integer as an input. And then generates a new number where all the digits are sorted in an descending order.
Example: 1342 => 4321 5791 => 9751
Scroll down for the solution of this programming exercise.
public static int SortDigits(int num) { //Oh boy.. We can solve this coding problem //in a 1000 different ways. But since the goal is //to learn new things, I am going to use a lot of //functions and explain them. //first lets convert "num" to string and then to char array. char[] digits = num.ToString().ToCharArray(); //we needed this array so we can sort it. Array.Sort(digits); //but we need a reverse sorting Array.Reverse(digits); //now we have a char array, but we need an integer string str = new string(digits); return int.Parse(str); //and that's how we convert char array to a string //I want to stress that we cannot use = operator //we cannot do "str=digits". Because they are different types //s is a string and digits is an array. //Do be safe, assume that we can use the Assignment operator "=" //only on the same data types. }