###### tags: `Leetcode` `medium` `sort` `python` `c++`
# 179. Largest Number
## [題目連結:] https://leetcode.com/problems/largest-number/description/
## 題目:
Given a list of non-negative integers ```nums```, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
**Example 1:**
```
Input: nums = [10,2]
Output: "210"
```
**Example 2:**
```
Input: nums = [3,30,34,5,9]
Output: "9534330"
```
## 解題相法:
* 題目為給一數組,求將其所有字符組成最大值的字串
## Python
* 使用compare比較:
* **def __ lt __()**: less than
* 比較:str(x) + str(y) > str(y) + str(x)
``` python=
class Solution(object):
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
ans = sorted([str(val) for val in nums], key=compare)
ans = ''.join(ans)
return ans if ans[0]!='0' else '0'
class compare(str): #less than
def __lt__(a,b):
return a+b>b+a
result = Solution()
nums = [3,30,34,5,9]
ans=result.largestNumber(nums)
print(ans)
```
## C++:
* 對於 bool compare():
* 需要加 **static** 否則會報錯
* 錯誤內容: reference to non-static member function must be called
* 說明: https://www.twblogs.net/a/5d660a9ebd9eee5327fe7083
``` cpp=
#include<bits/stdc++.h>
using namespace std;
class Solution{
public:
string largestNumber(vector<int>& nums){
string res;
//<algorithm>
sort(nums.begin(), nums.end(), compare);
if (nums[0]==0)
return "0";
for (auto val:nums){
res+=to_string(val);
}
return res;
}
static bool compare(int a, int b){
string str1=to_string(a);
string str2=to_string(b);
return str1+str2>str2+str1;
}
};
int main(){
Solution res;
vector<int> nums={3,30,34,5,9};
string ans=res.largestNumber(nums);
cout<<ans<<endl;
return 0; //9534330
}
```