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.

Have you met this question in a real interview? Yes
Example
Given [1, 20, 23, 4, 8], the largest formed number is 8423201.

分析

多使用系统的方法,不要重复的造轮子。

代码

public class Solution {
    /*
     * @param nums: A list of non negative integers
     * @return: A string
     */
    public String largestNumber(int[] nums) {
        // write your code here
        String x = Arrays.toString(nums);
        x = x.substring(1, x.length() - 1);
        String[] split = x.split(",");
        Arrays.sort(split, new Comparator() {

            @Override
            public int compare(String o1, String o2) {
                o1 = o1.trim();
                o2 = o2.trim();
                return (o2 + o1).compareTo(o1 + o2);
            }
        });
        StringBuilder sb = new StringBuilder();
        for (String str :
                split) {
            sb.append(str.trim());
        }
        while (sb.charAt(0) == '0'&& sb.length() > 1) {
            sb.deleteCharAt(0);
        }
        return sb.toString();
    }
}

你可能感兴趣的:(Largest Number(最大数))