首页 > 其他 > 详细

Largest Number

时间:2015-10-26 02:08:27      阅读:217      评论: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 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();
    }
}

?

Largest Number

原文:http://hcx2013.iteye.com/blog/2251754

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!