标签:
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.
Sort
#include <vector> #include <iostream> #include <algorithm> #include <sstream> using namespace std; class Solution { public: string largestNumber(vector<int> &num) { struct MyCompared { bool operator ()(int lft,int rgt) { long unsigned int lidx=1,ridx=1; while(lidx!=1000000000) if(lft>=10*lidx) lidx*=10; else break; while(ridx!=1000000000) if(rgt>=10*ridx) ridx*=10; else break; lidx*=10; ridx*=10; return lft*ridx+rgt > rgt*lidx+lft; } }myCompared; if(num.size()==0) return ""; sort(num.begin(),num.end(),myCompared); ostringstream os; if(num[0]==0) return "0"; for(int i =0;i<num.size();i++) os<<num[i]; return os.str(); } }; int main() { vector<int > num{10,2}; Solution sol; cout<<sol.largestNumber(num)<<endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/Azhu/p/4335800.html