Given a list of non-negative integers (nums). Find the largest number by arranging them. Constraints: len(nums) > 0
Explain the design concept of the
#include <algorithm>
#include <iostream>
#include <string>
#include <
using namespace std;
// A comparison function which
// is used by sort() in
// printLargest()
int myCompare(string X, string Y)
{
// first append Y at the end of X
string XY = X.append(Y);
// then append X at the end of Y
string YX = Y.append(X);
// Now see which of the two
// formed numbers is greater
return XY.compare(YX) > 0 ? 1 : 0;
}
// The main function that prints
// the arrangement with the
// largest value. The function
// accepts a vector of strings
void printLargest(vector<string> arr)
{
// Sort the numbers using
// library sort function. The
// function uses our comparison
// function myCompare() to compare two strings
sort(arr.begin(), arr.end(), myCompare);
for (int i = 0; i < arr.size(); i++)
cout << arr[i];
}
// Driver code
int main()
{
vector<string> arr;
int size;
string num;
cout<<"Enter the number of elements : ";
cin>> size;
for(int i=0;i<size;i++){
cin>>num;
arr.push_back(num);
}
printLargest(arr);
return 0;
Step by step
Solved in 2 steps