
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Find the largest number that can be formed with the given digits in C++
- Maximum possible time that can be formed from four digits in C++
- Maximum number of parallelograms that can be made using the given length of line segments in C++
- How to find the number of digits in a given number using Python?
- Maximum Number of Events That Can Be Attended in C++
- Maximum number of candies that can be bought in C
- How many numbers can be formed by arranging the digits of the number 211 ?
- Find smallest number with given number of digits and sum of digits in C++
- JavaScript Program to Find Maximum value possible by rotating digits of a given number
- Maximum number of threads that can be created within a process in C
- Program to find maximum number of package that can be bought by buyers in C++
- Problem to Find Out the Maximum Number of Coins that Can be Collected in Python
- Maximum number of segments that can contain the given points in C++
- C++ program to find out the maximum number of cells that can be illuminated
- Find the Largest number with given number of digits and sum of digits in C++

Advertisements