首页 > 其他 > 详细

*Largest Number

时间:2015-10-09 07:01:00      阅读:204      评论: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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 

 1 class NumbersComparator implements Comparator<String> {
 2     @Override
 3     public int compare(String s1, String s2) {
 4         return (s2 + s1).compareTo(s1 + s2);
 5     }
 6 }
 7 
 8 public class Solution {
 9     
10     public String largestNumber(int[] nums) {
11         String[] strs = new String[nums.length];
12         for (int i = 0; i < nums.length; i++) {
13             strs[i] = Integer.toString(nums[i]);
14         }
15         Arrays.sort(strs, new NumbersComparator());
16         StringBuilder sb = new StringBuilder();
17         for (int i = 0; i < strs.length; i++) {
18             sb.append(strs[i]);
19         }
20         String result = sb.toString();
21         int index = 0;
22         while (index < result.length() && result.charAt(index) == ‘0‘) {
23             index++;
24         }
25         if (index == result.length()) {
26             return "0";
27         }
28         return result.substring(index,result.length());
29     }
30 }

 

*Largest Number

原文:http://www.cnblogs.com/hygeia/p/4862796.html

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