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

179. Largest Number

时间:2017-10-25 21:32:42      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:log   rri   number   大数   case   sort   div   valueof   integer   

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.

含义:给定多个非负数,将他们排列成一个最大数,用string返回

 

 1     public String largestNumber(int[] nums) {
 2         if(nums == null || nums.length == 0)
 3             return "";
 4 
 5         // Convert int array to String array, so we can sort later on
 6         String[] s_num = new String[nums.length];
 7         for(int i = 0; i < nums.length; i++)
 8             s_num[i] = String.valueOf(nums[i]);
 9 
10         // Comparator to decide which string should come first in concatenation
11         Comparator<String> comp = new Comparator<String>(){
12             @Override
13             public int compare(String str1, String str2){
14                 String s1 = str1 + str2;
15                 String s2 = str2 + str1;
16                 return s2.compareTo(s1); // reverse order here, so we can do append() later
17             }
18         };
19 
20         Arrays.sort(s_num, comp);//由顶到底,前一个元素加后一个元素的值,大于后一个元素加前一个元素的值
21         // An extreme edge case by lc, say you have only a bunch of 0 in your int array
22         if(s_num[0].charAt(0) == ‘0‘)
23             return "0";
24 
25         StringBuilder sb = new StringBuilder();
26         for(String s: s_num)
27             sb.append(s);
28 
29         return sb.toString();        
30     }

 

179. Largest Number

标签:log   rri   number   大数   case   sort   div   valueof   integer   

原文地址:http://www.cnblogs.com/wzj4858/p/7731612.html

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