# 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.

## 题目链接：

####思路分析

We want to compare the digit of each numbers and sort with bigger digit in the left to front. So we could convert each number to string first, then compare each number’s string value and sort bigger string to front. After sort, use a string builder to contain the final result.

remember to solve a corner case like all zero value in nums array.
####代码

class Solution {
public String largestNumber(int[] nums) {
if (nums.length == 0){
return "0";
}
String[] strs = new String[nums.length];
for (int i = 0; i < nums.length; i++){
strs[i] = String.valueOf(nums[i]);
}
Comparator<String> cmp = new Comparator<String>(){
@Override
public int compare(String str1, String str2){
String s1 = str1 + str2;
String s2 = str2 + str1;
return s2.compareTo(s1);
}
};
Arrays.sort(strs, cmp);
//corner case if nums only has a bunch of zero.
if (strs[0].charAt(0) == '0'){
return "0";
}
StringBuilder sb = new StringBuilder();
for (String str : strs){
sb.append(str);
}
return sb.toString();
}
}

class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> str;
for (auto i : nums)
str.push_back(to_string(i));
sort(str.begin(), str.end(), [](string& s1, string& s2){ return s1 + s2 > s2 + s1;});
string res = "";
for (auto s : str)
res += s;
while (res[0] == '0' && res.length() > 1)
res.erase(0, 1);
return res;
}
};


####反思

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120