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

[leed code 179] Larges Number

时间:2015-02-09 00:43:28      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

1 题目

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.

2 方法

刚开始就误入歧途,准备按字符来比较,结果逻辑各种复杂,网上查了查,结果发现直接比较两个连起来的字符串要简单的多。比如字符串a和字符串b,比较ab和ba的大小就搞定了。

3 代码

     public String largestNumber(int[] num){
            String[] strArray = new String[num.length];
            for (int i = 0; i < num.length; i++) {
                strArray[i] = Integer.toString(num[i]);
            }
            strArray = this.anotherSort(strArray);//(strArray);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < strArray.length; i++) {
                sb.append(strArray[i]);
            }
            String out = sb.toString();
            if(out.charAt(0) == ‘0‘) return "0";
            return out;
        }
    public static String[] anotherSort(String[] strSort) {
        String temper = "";
        for (int i = 0; i < strSort.length; i++) {
            for (int j = i + 1; j < strSort.length; j++) {
                String add1 = strSort[i] + strSort[j];
                String add2 = strSort[j] + strSort[i];
                int out = add1.compareTo(add2);
                if (out < 0) {
                    temper = strSort[i];
                    strSort[i] = strSort[j];
                    strSort[j] = temper;
                }
            }
        }
        return strSort;
    }    

 

[leed code 179] Larges Number

标签:

原文地址:http://www.cnblogs.com/lingtingvfengsheng/p/4280636.html

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