Maximum number from the digits of a given number


Given a number (integer), find the maximum number you can form by using all the digits of the given number.
Eg.
Given number: 28492
Maximum number: 98422


Possible Solution:
The funda here is to get the digits and re-arrange them in descending order. So what you need basically is a frequency table to count the frequency of each of the digits in the given number. Then form the number by putting the digits in descending order.
Here is a sample C code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int getMax(int num)
{
  int freqTab[10] = {0,}; /* initializing with 0 */
  int count = 0;
  int digit;
  while(num)
  {
    digit = num % 10;
    freqTab[digit]++;
    num = num / 10;
    count++;
  }
  num = 0;
  index = 9; 
  while(count)
  {
    if(freqTab[index] > 0)
    {
      num = num * 10 + index;
      freqTab[index]--;
      count--;
    }
    else  index--; 
  }
  return num;
}

0 comments:

Post a Comment