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.
解题思路:
自定义一种排序规则,然后对原数组排序即可。最开始我想逐个字符分析来排序规则,发觉太麻烦了,考虑的东西太多。对于字符串s1和s2,判断s1>s2只需要s1s2>s2s1即可,结果驱动型。
注意若参数为0,0,最终结果为0。
另外,整数转字符串的方法有没有更好的?
string intToString(int a){
string s = "";
stack<char> stack;
while (a != 0){
stack.push('0' + a%10);
a /= 10;
}
while (!stack.empty()){
s += stack.top();
stack.pop();
}
return s==""? "0":s;
}
//a是否字符串大于等于b
bool compareGreater(int a, int b){
string sa = intToString(a), sb = intToString(b);
string s1 = sa + sb;
string s2 = sb + sa;
return s1 > s2 ? true : false;
}
class Solution {
public:
string largestNumber(vector<int> &num) {
std::sort(num.begin(), num.end(), compareGreater);
int len = num.size();
if(len==0 || num[0]==0){
return "0";
}
string result = "";
for (int i = 0; i<len; i++){
result += intToString(num[i]);
}
return result;
}
};
string intToString(int a){
string s = "";
stack<char> stack;
while (a != 0){
stack.push('0' + a%10);
a /= 10;
}
while (!stack.empty()){
s += stack.top();
stack.pop();
}
return s==""? "0":s;
}
//a是否字符串大于等于b
bool compareGreater(int a, int b){
string sa = intToString(a), sb = intToString(b);
string s1 = sa + sb;
string s2 = sb + sa;
return s1 > s2 ? true : false;
}
class Solution {
public:
string largestNumber(vector<int> &num) {
std::sort(num.begin(), num.end(), compareGreater);
int len = num.size();
if(len==0 || num[0]==0){
return "0";
}
string result = "";
for (int i = 0; i<len; i++){
result += intToString(num[i]);
}
return result;
}
};