2015年9月4日星期五

Largest Number

Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.

public class Solution {
    public String largestNumber(int[] nums) {
        StringBuilder sb = new StringBuilder();
        String tks[] = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            tks[i] = Integer.toString(nums[i]);
        }
        Arrays.sort(tks, new Comparator<String>() {
          public int compare(String s1, String s2) {
            String str1 = s1 + s2;
            String str2 = s2 + s1;
            return -1 * str1.compareTo(str2);
          }
        }
        );
        if (tks[0].charAt(0) == '0') return "0";
        for (String tk : tks) {
            sb.append(tk);
        }
        return sb.toString();
    }
}

没有评论:

发表评论