-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathForm the largest number
56 lines (43 loc) · 1.33 KB
/
Form the largest number
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
//Form the largest number
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine();
while(t-- > 0) {
String input = sc.nextLine();
String[] numbers = input.split(" ");
int[] arr = new int[numbers.length];
for(int i = 0; i < numbers.length; i++) {
arr[i] = Integer.parseInt(numbers[i]);
}
Solution ob = new Solution();
String ans = ob.findLargest(arr);
System.out.println(ans);
System.out.println("~");
}
sc.close();
}
}
class Solution {
String findLargest(int[] arr) {
ArrayList<String> numbers = new ArrayList<>();
for(int ele : arr) {
numbers.add(Integer.toString(ele));
}
Collections.sort(numbers, (s1, s2) -> myCompare(s1, s2) ? -1 : 1);
if(numbers.get(0).equals("0")) {
return "0";
}
StringBuilder res = new StringBuilder();
for(String num : numbers) {
res.append(num);
}
return res.toString();
}
static boolean myCompare(String s1, String s2) {
return (s1 + s2).compareTo(s2 + s1) > 0;
}
}