Leetcode 179: 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.

 

 1 public class Solution {
 2     public class NumberComparer : IComparer<int>
 3     {
 4         public int Compare(int a, int b)
 5         {
 6             int da = 10, db = 10, t1 = a, t2 = b;
 7             
 8             while (t1 >= 10)
 9             {
10                 t1 = t1 / 10;
11                 da *= 10;
12             }
13             
14             while (t2 >= 10)
15             {
16                 t2 = t2 / 10;
17                 db *= 10;
18             }
19             
20             return (b * da + a) - (a * db + b);  
21         }
22     }
23     
24     public string LargestNumber(int[] nums) {
25         Array.Sort(nums, new NumberComparer());
26         
27         var sb = new StringBuilder();
28         bool leadingZero = true;
29         
30         foreach (var n in nums)
31         {
32             if (n == 0 && leadingZero) continue;
33             
34             leadingZero = false;
35                 
36             sb.Append(n);
37         }
38         
39         if (sb.Length == 0) sb.Append(0);
40         
41         return sb.ToString();
42     }
43 }

 

posted @ 2017-11-29 05:33  逸朵  阅读(126)  评论(0)    收藏  举报