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

LeetCode-Largest Number

时间:2016-07-16 07:02:06      阅读:118      评论: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.
public class Solution {
    public String largestNumber(int[] nums) {
        int n=nums.length;
        if(n<1){
            return "";
        }
        String[] strs = new String[n];
        for(int i=0; i<nums.length; i++){
            strs[i]=Integer.toString(nums[i]);
        }
        Arrays.sort(strs, new Cmp());
        
        
        String ans="";
        for(int i=n-1; i>=0; i--){
            ans=ans+strs[i];
        }
        //remove 0‘s in fornt of the string
        int i=0;
        while(i<ans.length() && ans.charAt(i)==‘0‘){
            i++;
        }
        if(i == ans.length()){
            return "0";
        }
        return ans.substring(i);
    }
    private class Cmp implements Comparator<String>{
        public int compare(String a, String b){
            String ab=a+b;
            String ba=b+a;
            return ab.compareTo(ba);
        }
    }
    
}

 

LeetCode-Largest Number

标签:

原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5675202.html

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