Given an array of elements find the largest possible number that can
be formed by using the elements of the array.
eg: 10 9
ans: 910
2 3 5 78
ans: 78532
100 9
ans: 9100
http://www.careercup.com/question?id=9334650
把字符串排个序,比较方法是循环比较各个字符,如果对应位的字符大于另一个字符串的对应位则返回true,否则false。思想就是类似于要把尽可能大的数位放在更高位。
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <algorithm> 5 using namespace std; 6 7 bool comp(const string &lhs, const string &rhs) 8 { 9 int len = max(lhs.size(), rhs.size()); 10 11 for(int i = 0; i < len; i++) 12 { 13 int lIndex = i % lhs.size(); 14 int rIndex = i % rhs.size(); 15 if (lhs[lIndex] > rhs[rIndex]) 16 return true; 17 else if (lhs[lIndex] < rhs[rIndex]) 18 return false; 19 } 20 21 return true; 22 } 23 24 string solve(vector<string> &a) 25 { 26 sort(a.begin(), a.end(), comp); 27 28 string s; 29 30 for(int i = 0; i < a.size(); i++) 31 s = s + a[i]; 32 33 return s; 34 } 35 36 int main() 37 { 38 vector<string> a; 39 a.push_back("10"); 40 a.push_back("9"); 41 cout << solve(a) << endl; 42 43 vector<string> b; 44 b.push_back("2"); 45 b.push_back("3"); 46 b.push_back("5"); 47 b.push_back("78"); 48 cout << solve(b) << endl; 49 50 vector<string> c; 51 c.push_back("100"); 52 c.push_back("9"); 53 cout << solve(c) << endl; 54 }