Find maximum number that can be formed using digits of a given number in C++


Suppose we have a number of n digits. We have to find the maximum number that can be obtained using all digits of digits of that number. So if the number is say 339625, then maximum number can be 965332.

From the problem, we can see that we can easily sort the digits in non-increasing order, then print them. But we can solve this using more efficient way. We can create one array of size 10 to store the frequency of each digit, then print the numbers from 9 to 0 accordingly.

Example

 Live Demo

#include <iostream>
#include <string>
using namespace std;
int maxNumFromNum(int num) {
   int freq[10] = {0};
   string str = to_string(num);
   for (int i=0; i<str.length(); i++)
   freq[str[i]-'0']++;
   int res = 0, mul = 1;
   for (int i = 0; i <= 9; i++) {
      while (freq[i] > 0) {
         res = res + (i * mul);
         freq[i]--;
         mul = mul * 10;
      }
   }
   return res;
}
int main() {
   int num = 339625;
   cout << "Maximum number: " << maxNumFromNum(num);
}

Output

Maximum number: 965332

Updated on: 18-Dec-2019

385 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements