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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
string largestNumber(vector<int>& nums) { vector<string> vec; for (auto num : nums) vec.push_back(to_string(num)); sort(vec.begin(), vec.end(), [](const string &a, const string &b) { int i = 0, j = 0; int tag1 = 0, tag2 = 0; while (tag1 < 2 && tag2 < 2) { if (i == a.length()) { i = 0; tag1++; } if (j == b.length()) { j = 0; tag2++; } if (a[i] < b[j]) return false; else if (a[i] > b[j]) return true; i++; j++; } return false; }); string res; for (auto kit : vec) res.append(kit); if (res.find_first_not_of(‘0‘) == -1) res = "0"; return res; }
原文:http://www.cnblogs.com/sdlwlxf/p/5158849.html