把数组排成最小的数

题目描述

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
 1 import java.util.*;
 2 
 3 /**
 4  * 
 5  * @author gentleKay
 6  * 题目描述
 7  * 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,
 8  * 打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},
 9  * 则打印出这三个数字能排成的最小数字为321323。
10  */
11 
12 public class Main32 {
13 
14     public static void main(String[] args) {
15         // TODO Auto-generated method stub
16         int[] numbers = {3,32,321};
17         String str = Main32.PrintMinNumber(numbers);
18         System.out.println(str);
19     }
20     
21     public static String PrintMinNumber(int [] numbers) {
22         if (numbers == null || numbers.length == 0) {
23             return "";
24         }
25         String[] str = new String[numbers.length];
26         for (int i=0;i<numbers.length;i++) {
27             str[i] = String.valueOf(numbers[i]);
28         }
29         Arrays.sort(str, new Comparator<String>() {
30             @Override
31             public int compare(String o1, String o2) {
32                 String c2 = o1+o2;
33                 String c3 = o2+o1;
34                 return c2.compareTo(c3);
35             }
36         });
37         
38         StringBuilder sb = new StringBuilder();
39         for (int i=0;i<numbers.length;i++) {
40             sb.append(str[i]);
41         }
42         return sb.toString();
43     }
44 
45 }
原文地址:https://www.cnblogs.com/strive-19970713/p/11160257.html