blob: 1ddff1e5a1b8d49f39924835bd3b8980f3e58760 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
String[] a = new String[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.next();
}
System.out.println(getLargestNumber(a));
}
public static String getLargestNumber(String[] numbers) {
List<String> numList = new ArrayList<String>(Arrays.asList(numbers));
String result = "";
String maxDigit = "0";
int indexHolder = 0;
while (numList.size() > 0) {
for (int i = 0; i < numList.size(); i++) {
if (compareLeadingDigit(numList.get(i), maxDigit)) {
maxDigit = numList.get(i);
indexHolder = i;
}
}
result = result + maxDigit;
maxDigit = "0";
numList.remove(indexHolder);
}
return result;
}
public static boolean compareLeadingDigit(String s, String maxDigit) {
//Oh my god, the algorithm for this comparison was so clever mentioned
//by bytwigorlimerick in this page:
//https://courses.edx.org/courses/course-v1:UCSanDiegoX+ALGS200x+2T2017/discussion/forum/course/threads/5a427dbf44a15008cd000701
//This solved the problem nicely and easily, so elegant!
return Integer.parseInt(s + maxDigit) > Integer.parseInt(maxDigit + s);
// if (s.length() == maxDigit.length())
// return Integer.parseInt(s) > Integer.parseInt(maxDigit);
// if (s.length() < maxDigit.length()) {
// if (s.charAt(0) > maxDigit.charAt(0)) {
// return true;
// } else if (s.charAt(0) < maxDigit.charAt(0)) {
// return false;
// } else if (s.charAt(0) > maxDigit.charAt(1)) {
// return true;
// } else if (s.length() == 1) {
// if (s.charAt(0) > maxDigit.charAt(1))
// return true;
// else
// return false;
// } else
// return compareLeadingDigit(s.substring(1), maxDigit.substring(1));
// } else {
// return !compareLeadingDigit(maxDigit, s);
// }
}
}
|