您的位置:首页 > 编程语言 > C语言/C++

[LeetCode] Largest Number

2015-04-10 19:53 246 查看


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;
}
};


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode