Find maximum number that can be formed using digits of a given number - GeeksforGeeks

01 Feb, 2022
Given a number, write a program to find a maximum number that can be formed using all of the digits of this number.Examples:  
Input : 38293367
Output : 98763332

Input : 1203465
Output: 6543210
 
Simple Approach: The simple method to solve this problem is to extract and store the digits of the given number in an integer array and sort this array in descending order. After sorting the array, print the elements of the array. Time Complexity: O( N log N ), where N is the number of digits in the given number.Efficient approach : We know that the digits in a number will range from 0-9, so the idea is to create a hashed array of size 10 and store the count of every digit in the hashed array that occurs in the number. Then traverse the hashed array from index 9 to 0 and calculate the number accordingly.Below is the implementation of above efficient approach:  
C++
Java
Python3
C#
PHP
Javascript
// CPP program to print the maximum number// from the set of digits of a given number#include <bits/stdc++.h>using namespace std; // Function to print the maximum numberint printMaxNum(int num){    // hashed array to store count of digits    int count[10] = {0};     // Converting given number to string    string str = to_string(num);     // Updating the count array    for (int i=0; i<str.length(); i++)        count[str[i]-'0']++;     // result is to store the final number    int result = 0, multiplier = 1;     // Traversing the count array    // to calculate the maximum number    for (int i = 0; i <= 9; i++)    {        while (count[i] > 0)        {            result = result + (i * multiplier);            count[i]--;            multiplier = multiplier * 10;        }    }     // return the result    return result;} // Driver program to test above functionint main(){    int num = 38293367;    cout << printMaxNum(num);    return 0;}
// Java program to print the maximum number// from the set of digits of a given numberpublic class GFG{    // Function to print the maximum number    static int printMaxNum(int num)    {        // hashed array to store count of digits        int count[] = new int[10];                 // Converting given number to string        String str = Integer.toString(num);                 // Updating the count array        for(int i=0; i < str.length(); i++)            count[str.charAt(i)-'0']++;                 // result is to store the final number        int result = 0, multiplier = 1;                 // Traversing the count array        // to calculate the maximum number        for (int i = 0; i <= 9; i++)        {            while (count[i] > 0)            {                result = result + (i * multiplier);                count[i]--;                multiplier = multiplier * 10;            }        }              // return the result        return result;    }         // Driver program to test above function    public static void main(String[] args)    {        int num = 38293367;        System.out.println(printMaxNum(num));    }}// This code is contributed by Sumit Ghosh
# Python program to print the maximum number# from the set of digits of a given number # Function to print maximum numberdef printMaximum(inum):     # Hashed array to store count of digits    count = [0 for x in range(10)]     # Converting given number to string    string = str(num)     # Updating the count array    for i in range(len(string)):        count[int(string[i])] = count[int(string[i])] +  1     # Result stores final number    result = 0    multiplier = 1     # traversing the count array    # to calculate the maximum number     for i in range(10):        while count[i] > 0:            result = result + ( i * multiplier )            count[i] = count[i] - 1            multiplier = multiplier * 10     # return the result    return result # Driver codenum = 38293367print(printMaximum(num)) # This code is contributed by Harshit Agrawal
// C# program to print the maximum number// from the set of digits of a given numberusing System; class GFG{ // Function to print the maximum numberstatic int printMaxNum(int num){    // hashed array to store    // count of digits    int []count = new int[10];         // Converting given number    // to string    String str = num.ToString();         // Updating the count array    for(int i = 0; i < str.Length; i++)        count[str[i] - '0']++;         // result is to store the    // final number    int result = 0, multiplier = 1;         // Traversing the count array    // to calculate the maximum number    for (int i = 0; i <= 9; i++)    {        while (count[i] > 0)        {            result = result + (i * multiplier);            count[i]--;            multiplier = multiplier * 10;        }    }     // return the result    return result;} // Driver Codepublic static void Main(){    int num = 38293367;    Console.Write(printMaxNum(num));}} // This code is contributed// by PrinciRaj1992
<?php // Php program to print the maximum number// from the set of digits of a given number // Function to print the maximum numberfunction printMaxNum($num){    // hashed array to store count of digits    $count = array_fill(0,10, NULL);      // Converting given number to string    $str = (string)$num;      // Updating the count array    for ($i=0; $i<strlen($str); $i++)        $count[ord($str[$i])-ord('0')]++;      // result is to store the final number    $result = 0;    $multiplier = 1;      // Traversing the count array    // to calculate the maximum number    for ($i = 0; $i <= 9; $i++)    {        while ($count[$i] > 0)        {            $result = $result + ($i * $multiplier);            $count[$i]--;            $multiplier = $multiplier * 10;        }    }      // return the result    return $result;}  // Driver program to test above function     $num = 38293367;    echo printMaxNum($num);?>
<script>// Javascript program to print the maximum number// from the set of digits of a given number         // Function to print the maximum number    function printMaxNum(num)    {        // hashed array to store count of digits        let count = new Array(10);        for(let i=0;i<count.length;i++)        {            count[i]=0;        }                 // Converting given number to string        let str = num.toString();                   // Updating the count array        for(let i=0; i < str.length; i++)            count[str[i]-'0']++;                   // result is to store the final number        let result = 0, multiplier = 1;                   // Traversing the count array        // to calculate the maximum number        for (let i = 0; i <= 9; i++)        {            while (count[i] > 0)            {                result = result + (i * multiplier);                count[i]--;                multiplier = multiplier * 10;            }        }                // return the result        return result;    }         // Driver program to test above function    let num = 38293367;    document.write(printMaxNum(num));         //This code is contributed by avanitrachhadiya2155     </script>
Output:  
98763332
Time Complexity: O( N ), where N is the number of digits in the given number. Note: For very large numbers we can use strings to take input instead of storing input in integer data type. 
YouTubeGeeksforGeeks507K subscribersFind maximum number that can be formed using digits of a given number | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:25•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=bywFHWV0NS0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
princiraj1992
ukasp
avanitrachhadiya2155
surindertarika1234
amartyaghoshgfg
number-digits
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Print all possible combinations of r elements in a given array of size n
Sieve of Eratosthenes
Operators in C / C++
Program for factorial of a number
The Knight's tour problem | Backtracking-1
Program for Decimal to Binary Conversion