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 is very large, so you need to return a string instead of an integer.
Set A has x position, B has y bit if a is in front, then A*10^y+b>b*10^x+a uses the idea to sort
1 classSolution {2 Public:3 4 Static BOOLcmpintAintb)5 {6 intDigita=1;7 intdigitb=1;8 9 intTmpa=A;Ten One while(tmpa>=Ten) A { -digita++; -Tmpa/=Ten; the } - - inttmpb=b; - while(tmpb>=Ten) + { -digitb++; +Tmpb/=Ten; A } at - returnA*pow (Ten, DIGITB) +b>b*pow (Ten, Digita) +A; - - } - - stringLargestnumber (vector<int> &num) { in - sort (Num.begin (), Num.end (), CMP); to + stringresult=""; - the for(intI=0; I<num.size (); i++) * { $result+=to_string (Num[i]);Panax Notoginseng } - the if(result[0]=='0') result="0"; + A returnresult; the + } -};
Another way to do this is to convert the numbers into strings and then compare them by string concatenation, so the CMP function will be much better.
1 classSolution {2 Public:3 4 Static BOOLcmpstringAstringb)5 {6 returna+b>b+A;7 }8 9 stringLargestnumber (vector<int> &num) {Ten One intn=num.size (); Avector<string>strnum (n); - for(intI=0; i<n;i++) - { thestrnum[i]=to_string (Num[i]); - } - - sort (Strnum.begin (), Strnum.end (), CMP); + - stringresult=""; + A for(intI=0; i<n;i++) at { -result+=Strnum[i]; - } - - if(result[0]=='0') result="0"; - in returnresult; - } to};
"Leetcode" largest number