Sagar's Gift

Today is Sagar's birthday. He got an array of numbers as a gift from his father. His father told him that he has another gift if Sagar is able to make the largest number by concatenating the numbers and swapping the digits of numbers. Help Sagar to make the largest number from the given numbers.

Example:

Input:  n = 5, a = {1, 2, 20, 31, 5}
Output: 5322110

Approach

C++

#include <bits/stdc++.h>
using namespace std;

string gift(int nint a[])
{

    vector<intv;
    for (int i = 0i < ni++)
    {
        int j = a[i];
        if (j == 0)
            v.push_back(0);
        while (j)
        {
            v.push_back(j % 10);
            j = j / 10;
        }
    }
    string str = "";
    sort(v.begin(), v.end());
    for (int i = v.size() - 1i >= 0i--)
        str += to_string(v[i]);

    return str;
}
int main()
{
    int n = 5;

    int a[n] = {1220315};

    cout << gift(na<< "\n";

    return 0;
}


No comments:

Post a Comment