`
hcx2013
  • 浏览: 88712 次
社区版块
存档分类
最新评论

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.

 

public class Solution {
    public String largestNumber(int[] nums) {
        int len = nums.length;
        if (len < 1) {
        	return "";
        }
        String[] strs = new String[len];
        for (int i = 0; i < len; i++) {
        	strs[i] = String.valueOf(nums[i]);
		}
        Arrays.sort(strs, new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				// TODO Auto-generated method stub
				return (o1 + o2).compareTo(o2 + o1);
			}
		});
        StringBuffer res = new StringBuffer();
        for (int i = len-1; i >= 0; i--) {
        	res.append(strs[i]);
		}
        int i = 0;
        while (i < len && res.charAt(i) == '0') {
        	i++;
        }
        if (i == len) {
        	return "0";
        }
        return res.substring(i).toString();
    }
}

 

0
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics