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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
- string to_convert(int a) {
- stringstream ss;
- ss << a;
- string tmp;
- ss >> tmp;
- ss.clear();
- ss.str("");
- return tmp;
- }
- bool cmp(int a,int b) {
- string tmp1 = to_convert(a);
- string tmp2 = to_convert(b);
- string first = tmp1 + tmp2;
- string second = tmp2 + tmp1;
- return first>second;
- }
- class Solution {
- public:
- string largestNumber(vector<int> &num) {
- sort(num.begin(),num.end(),cmp);
- string result = "";
- for(int i=0;i<num.size();i++) {
- result += to_convert(num[i]);
- }
- int pos=0;
- while(pos<result.size()-1 && result[pos] == '0') pos++;
- result = result.substr(pos);
- return result;
- }
- };
处理对象转换思路更好些

浙公网安备 33010602011771号