Topic description
Given n positive integers (n≤20), join them in a row to form the largest multi-bit integer.
For example: when n=3, the largest integer formed by the concatenation of 3 integers 13, 312, and 343 is: 34331213
Another example: when n=4, the largest integer formed by the concatenation of 4 integers 7, 13, 4, and 246 is: 7424613
Input and output format
Input format:
The first line, a positive integer n.
The second line, n positive integers.
Output format:
a positive integer representing the largest integer
Input and output example
Input Example #1:
Copy
3 13 312 343
Output Sample #1:
Copy
34331213 Error
-prone point: simple comparison of size. What we need to compare is the number size of the two strings. If you simply compare the size of a string, you will lose the overall connection. For
example, a simple comparison of 300 30
is of course 30030, but this is not the largest. Instead, 30300
compares the size of cmp in sort to a+b>b+a, and then the maximum value of the entire number is compared one by one. The
code is as follows:
#include<iostream>
#include<string>
#include <algorithm>
using namespace std;
bool cmp(string a, string b)
{
return a+b > b+a;
}
int main()
{
string num[21];
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> num[i];
sort(num, num + n, cmp);
for (int i = 0; i < n; i++)
cout << num[i];
cout << endl;
return 0;
}