想的方法太笨了,开始想的是一位一位的比较
答案重写Collections.sort的compare方法很好,值得多看学习
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(in.nextInt()); } Collections.sort(list, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { // TODO Auto-generated method stub String s1 = String.valueOf(o1); String s2 = String.valueOf(o2); //降序 return (s2 + s1).compareTo(s1 + s2); //升序 //return (s1 + s2).compareTo(s2 + s1); } }); for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i)); } System.out.println(); } } }
文章来源: 【真题编程】2017猪八戒