Largest Number

Given a list of non negative integers, arrange them such that they form the largest number.

 Notice

The result may be very large, so you need to return a string instead of an integer.

Example

Given [1, 20, 23, 4, 8], the largest formed number is 8423201.

分析:

这里把所有的数转换成string, 然后排序。但是string怎么比较大小呢?这里不能用一般比较方法,需要比较str1+str2 和str2 + str1 来确定哪个大。

 1 public class Solution {
 2     public String largestNumber(int[] num) {
 3         if (num == null || num.length == 0) return "";
 4 
 5         String[] strNum = new String[num.length];
 6         for (int i = 0; i < num.length; i++) {
 7             strNum[i] = String.valueOf(num[i]);
 8         }
 9 
10         Arrays.sort(strNum, (String str1, String str2) -> (str1 + str2).compareTo(str2 + str1));
11         StringBuilder sb = new StringBuilder();
12 
13         for (int i = strNum.length - 1; i >= 0; i--) {
14             sb.append(strNum[i]);
15         }
16         
17         while (sb.length() > 1 && sb.charAt(0) == '0') {
18             sb.deleteCharAt(0);
19         }
20         return sb.toString();
21     }
22 }

 

 

posted @ 2016-07-05 09:48  北叶青藤  阅读(191)  评论(0)    收藏  举报