题目
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: “210”
Example 2:
Input: [3,30,34,5,9]
Output: “9534330”
【输入】n个非负数,n大于1小于1000,序列n长度小于1000;
【输出】n个非负数组成的最大值。
例如:
【输入】
3 30 34 5 9
【输出】
9534330
思路
将int
转换为string
,将字符串排序即可。用到sort
函数,cmp
函数比较两个字符串加在一起后的顺序。
代码
#include <bits/stdc++.h>
using namespace std;
class LargestNumber
{
public:
string largestNumber(vector<int> &nums);
static bool cmp(string &fir, string &sec);
};
int main()
{
vector<int> mylist;
int item;
string num;
while (cin >> item)
{
mylist.push_back(item);
}
LargestNumber sol;
num = sol.largestNumber(mylist);
cout << num << endl;
system("pause");
return 0;
}
string LargestNumber::largestNumber(vector<int> &nums)
{
int size = nums.size();
vector<string> str;
for(int i = 0; i < size; i++)
{
str.push_back(to_string(nums[i]));//转化为string
}
sort(str.begin(), str.end(), cmp);
int strSize = str.size();
string ans;
for(int i = 0; i < strSize; i++)
{
ans += str[i];
}
return ans;
}
bool LargestNumber::cmp(string &fir, string &sec)
{
return (fir + sec) > (sec + fir);//true即fir+sec形式更大,参数里fir放前边
}
一些问题
- 比较函数中,结果为true即fir+sec形式更大,参数里前边的就放在前边。
- 用了
vector
分别放入int
和string
,使用to_string
函数。 sort(str.begin(),str.end(),cmp)
为sort
的用法。