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.
对于每两个数字所能组成的字符串进行大小排序,然后顺序输出,注意0的特殊处理。
bool com(string a,string b) { return (a+b)>(b+a); } class Solution { public: string to_str(long long n) { string str=""; if(n==0) { str+='0'; return str; } long long tmp=n; long long power=1; int icount=0; while (tmp) { tmp/=10; power*=10; icount++; } power/=10; tmp=n; for (int i=0;i<icount;i++) { long long d=tmp/power; str+=char('0'+d); tmp-=d*power; power/=10; } return str; } string largestNumber(vector<int> &num) { if(num.empty())return ""; int n=num.size(); vector<string> str; for(int i=0;i<n;i++) { str.push_back(to_str(num[i])); } sort(str.begin(),str.end(),com); string res=""; for(int i=0;i<n;i++) { if(str[i]!="0")res+=str[i]; else { if(res!="")res+=str[i]; } } if(res=="")res+="0"; return res; } };