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.
sort the number first.
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool myCompare(const int& a, const int& b) {
return to_string(a) + to_string(b) > to_string(b) + to_string(a);
}
string largestNumber(vector<int>& nums) {
if(nums.size() == 0) return "";
sort(nums.begin(), nums.end(), myCompare);
string tmp = to_string(nums[0]);
for(int i = 1; i < nums.size(); ++i) {
tmp += to_string(nums[i]);
}
return tmp;
}
int main(void) {
vector<int> nums{0, 9, 8, 7, 6, 5, 4, 3, 2, 1};
string tmp = largestNumber(nums);
cout << tmp << endl;
}
247




被折叠的 条评论
为什么被折叠?



