Rearrange the numbers of your numbers

Rearrange your numbers programming exercise.

Is there a way to make money? Fast way ? Perhaps if there was way to rearrange the numbers in your bank account…

You are given an array of digits in form of character array. Construct the largest possible number from them. Then spend them wisely 🙂

Example:
'1','2','3' => 321
'5','2','8','0' => 8520

Scroll down for the solution of this coding problem.

Well this is a bit of a Math trick. If you didn’t already saw it, there it is:

If we reverse sort the array, we automatically will have the largest number!

1) First lets get the digits of the number, and put it in some sort of array. I am going to use ToString() to convert the number to a string and then ToArray() to convert the string to an char array.
2) Then Array.Sort() and Array.Reverse() to sort it and then reverse it.
3) And finally int.Parse() will convert a string to an integer … But first we need to convert the char array to a string. And this new string(array) is the way to do it.

    public static int MaxNumber(int n)
    {
        char[] num = n.ToString().ToArray();
        Array.Sort(num); Array.Reverse(num);
        return int.Parse(new string(num));
    }

Afforce you don’t have to use so many functions. For example you can use this algorithm to get the digits of a number:

        List<int> digits = new List<int>();
        while (n>0)
        {
            digits.Add(n % 10);
            n = n / 10;
        }

Then reverse sort it. And then … Reverse the algorithm to get the number. But I am not going to show you how. This is only for real hackers 🙂