Robert Eisele
Engineer, Systems Architect and DBA

Codingame: The greatest number

Original Problem

Goal

You must print the greatest number using all the characters in the input, including the ten digits 0 to 9, the minus sign - and the decimal dot ..

Beware:
* The dot alone must not end a number, at least a digit is needed. For example, 98742. is refused, write 9874.2 instead.
* Trailing and leading zeros must be removed. Write -4 instead of -4.0000 and -5.65 instead of-5.6500.
Input
Line 1 : The number N of chars
Line 2: N chars on a single line separated with spaces
Output
The greatest number possible using all the input chars (but maybe without some zeros).
Constraints
1 ≤ N ≤ 10

Solution

We firstly separate the digits from the special characters and depending on whether we must minimize or maximize the number, we sort the digits ascending or descending and put the dot and minus-sign at the right place. After that we strip off all zeros at the end if the number contains a dot. If all zeros were removed this way, the trailing dot must be removed as well. To minimize the code size we can remove all these zero cleanings and just use parseFloat with the concatenated number:

var N = +readline()
var input = readline().split(" ")
var nums = input.filter(x => x != "." && x != "-").map(Number)

if (input.indexOf("-") === -1) {
  nums.sort((a, b) => b - a);
  if (input.indexOf(".") !== -1) {
    nums.splice(nums.length - 1, 0, ".")
  }
} else {
  nums.sort((a, b) => a - b)
  if (input.indexOf(".") !== -1) {
    nums.splice(1, 0, ".")
  }
  nums.unshift("-")
}
print(parseFloat(nums.join("")))

« Back to problem overview