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.
第一次写的,觉得不是最好的方法。直接字符串比较会比较好。
bool more(const int & a,const int & b){
unsigned long long ac=(unsigned long long)a,ad=(unsigned long long)a;
unsigned long long bc=(unsigned long long)b,bd=(unsigned long long)b;
bool flag = true;
while(ac>=0&&flag){
bc*=10;
ac/=10;
if(ac==0) flag = false;
}
bc+=a;
flag = true;
while(bd>=0&&flag){
ad*=10;
bd/=10;
if(bd==0) flag = false;
}
ad+=b;
return ad>bc;
}
class Solution {
public:
string largestNumber(vector<int> &num) {
string s = "";
sort(num.begin(),num.end(),more);
bool flag = false;
for(int i=0;i<num.size();i++){
if(num[i]!=0){
s+=to_string(num[i]);
flag = true;
}
else if(flag){
s+=to_string(num[i]);
}
}
if(flag==false) s="0";
return s;
}
};
第二次
bool more(const int & a,const int & b){
int
return (a+b)>(b+a);
}
class Solution {
public:
string largestNumber(vector<int> &num) {
vector<string> str;
for(int i=0;i<num.size();i++){
str.push_back(to_string(num[i]));
}
sort(str.begin(),str.end(),more);
string s = "";
bool flag = false;
//sort(num.begin(),num.end(),more);
for(int i=0;i<str.size();i++){
if(str[i]!="0"){
s+=str[i];
flag = true;
}
else if(flag == true){
s+=str[i];
}
}
if(flag==false) s = "0";
return s;
}
};