I want to permute the digits of an int in a way that the result is the biggest possible permutation. This is easily done like this:
//how to deal with really large ints e.g.int32.MaxValue goes here
// in this case the algorithm would need to round down to the largest possible value
// but still needs to be less than int32.MaxValue
//This code will just handle normal values <int32.MaxValue
public static int Max(int number)
{
var numberAsCharArray = number.ToString().OrderByDescending(c => c).ToArray();
var largestNumberAsString = new string(numberAsCharArray);
return Int32.Parse(largestNumberAsString);
}
However, when the input has the same number of digits as Int32.MaxValue
and contains at least one high digit, this digit will go to the first position making the result > Int32.MaxValue
and leading to an exception when converting to int.
How could I limit the result to be <= Int32.MaxValue
but within this limit still be the greatest possible permutation?
N.B. Negative numbers, e.g. -1234567890
are allowed as well as positive ones; in case of negative input, -
sign should be dropped: -1234567890
should produce 2147398650
output