
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Maximum Number from 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
Advertisements