LeetCode 179 Largest Number 贪心
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
Input: nums = [3,30,34,5,9]
Output: "9534330"
Solution
注意的一点是to_string
函数,然后排序即可
点击查看代码
class Solution {
public:
static inline bool compare(int a,int b){
string v1 = to_string(a) + to_string(b);
string v2 = to_string(b) + to_string(a);
return v1>v2;
}
string largestNumber(vector<int>& nums) {
sort(nums.begin(),nums.end(),compare);
//for(int i=0;i<n;i++)cout<<nums[i]<<" ";
bool check_zero = true;
for(int i=0;i<nums.size();i++){
if(nums[i]==0)continue;
else{
check_zero = false;
break;
}
}
if(check_zero){return "0";}
else{
string ans = "";
for(int i=0;i<nums.size();i++){
ans = ans+to_string(nums[i]);
}
return ans;
}
}
};