码迷,mamicode.com
首页 > 其他好文 > 详细

179-Largest Number

时间:2015-05-18 20:38:52      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

【题目】

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;
        }
    }
}

 

179-Largest Number

标签:

原文地址:http://www.cnblogs.com/hwu2014/p/4512744.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!