Jump to content

Largest int from concatenated ints: Difference between revisions

+Java
(+Java)
Line 87:
<lang j> maxnum&> 1 34 3 98 9 76 45 4 ; 54 546 548 60
998764543431 6054854654</lang>
=={{header|Java}}==
{{works with|Java|1.5+}}
This example sets up a comparator to order the numbers using <code>Collections.sort</code> as described in method #3 (padding and reverse sorting). It was also necessary to make a join method to meet the output requirements.
<lang java5>import java.util.*;
 
public class IntConcat {
private static Comparator<Integer> sorter = new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2){
String o1s = o1.toString();
String o2s = o2.toString();
if(o1s.length() == o2s.length()){
return o2.toString().compareTo(o1.toString());
}
 
int mlen = Math.max(o1s.length(), o2s.length());
while(o1s.length() < mlen * 2) o1s += o1s;
while(o2s.length() < mlen * 2) o2s += o2s;
return o2s.compareTo(o1s);
}
};
public static String join(List<?> things){
String output = "";
for(Object obj:things){
output += obj;
}
return output;
}
public static void main(String[] args){
LinkedList<Integer> ints1 = new LinkedList<Integer>();
ints1.addAll(Arrays.asList(1, 34, 3, 98, 9, 76, 45, 4));
Collections.sort(ints1, sorter);
System.out.println(join(ints1));
LinkedList<Integer> ints2 = new LinkedList<Integer>();
ints2.addAll(Arrays.asList(54, 546, 548, 60));
Collections.sort(ints2, sorter);
System.out.println(join(ints2));
}
}</lang>
Output:
<pre>998764543431
6054854654</pre>
=={{header|Perl 6}}==
<lang Perl 6>sub maxnum(@x) {
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.