A lot of people have rightly pointed out that this problem can be solved using a lexical comparison of strings. However, that's not all you need.
Consider the following example: [5, 50, 56]. A lexical comparison returns 56, 50, and 5, but that doesn't make the larger number (56, 5, 50 does)
import java.util.Comparator;
public class Problem9 {
private static Integer[] VALUES = {5, 2, 1, 9, 50, 56};
public static void main(String[] args) {
Arrays.sort(VALUES, new Comparator() {
public int compare(Integer lhs, Integer rhs) {
String v1 = lhs.toString();
String v2 = rhs.toString();
return (v1 + v2).compareTo(v2 + v1) * -1;
}
@Override
public int compare(Object o1, Object o2) {
throw new UnsupportedOperationException("Not supported yet.");
//To change body of generated methods, choose Tools | Templates.
}
});
String result = "";
for (Integer integer : VALUES) {
result += integer.toString();
}
System.out.println(result);
}
}
|
No comments:
Post a Comment