179-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.

【分析】

1.设置一个比较器Comparator,比较两个String按不同方式拼接后的数字的大小(如String a和b,parseLong(a+b)和parseLong(b+a))

2.考虑int的范围,当两个数字拼接后可能会超出int的范围,采用Long来拼接两个int

【算法实现】

public class Solution {
    public String largestNumber(int[] nums) {
        int len = nums.length;
        if(len<1)
            return "";
        String[] str = new String[len];
        for(int i=0; i<len; i++) {
            str[i] = String.valueOf(nums[i]);
        } 
        Arrays.sort(str,new Cmp());
        
        StringBuffer res = new StringBuffer();
        for(int i=0; i<len; i++) {
            res.append(str[i]);
        }
        
        String r = res.toString();
        int i = 0;
        while(i<len && r.charAt(i)=='0') {
            i++;
        }
        if(i==len)
            return "0";
        
        return res.toString();
    }
    
    class Cmp implements Comparator<String> {
        public int compare(String s1, String s2) {
            String a = s1.concat(s2);
            String b = s2.concat(s1);
            int res;
            if((Long.parseLong(b)-Long.parseLong(a))>0) {
                res = 1;
            }else if((Long.parseLong(b)-Long.parseLong(a))<0) {
                res = -1;
            }else {
                res = 0;
            }
            return res;
        }
    }
}

 

posted @ 2015-05-18 18:29  hwu_harry  阅读(106)  评论(0编辑  收藏  举报