Generating possible Minimum and Maximum number from a given number.

The problem is. You will be given a number. And you have to generate the most possible minimum & maximum number by swapping any two digits of the given number. You can swap only one time. The number can't contain 0 at first position.

For example:

Input:
132
101010
1212221

Output:
Min: 123 Max: 312
Min: 100011 Max: 111000
Min: 111222 Max: 2211221

My solution:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

int main()
{
    int t; //Test case
    cin>>t;

    for(int i=1;i<=t;i++)
    {
        string num;
        cin>>num;
        string sort_num=num, max_num=num, min_num=num;

        sort(sort_num.begin(),sort_num.end());

        char f_mx_e, s_mx_e, f_mi_e, s_mi_e;

        f_mx_e=sort_num[sort_num.length()-1];
        s_mx_e=sort_num[sort_num.length()-2];
        f_mi_e=sort_num[0];
        s_mi_e=sort_num[1];

        int f_mx_p=num.find(f_mx_e);
        int s_mx_p=num.find(s_mx_e);
        int f_mi_p=num.find(f_mi_e);
        int s_mi_p=num.find(s_mi_e);


        //For Min_num
        if(num[1]!='0' && num[0]!=f_mi_e)
            swap(min_num[0],min_num[f_mi_p]);
        if(num[1]!='0' && num[0]==f_mi_e && num[1]!=s_mi_e)
            swap(min_num[1],min_num[s_mi_p]);
        if(num[1]!='0' && num[0]!=f_mi_e && num[1]!=s_mi_e)
            min_num=min_num;


        //For Max_num
        if(num[0]!=f_mx_e)
            swap(max_num[0],max_num[f_mx_p]);
        if(num[0]==f_mx_e && num[1]!=s_mx_e)
            swap(max_num[1],max_num[s_mx_p]);
        if(num[0]!=f_mx_e && num[1]!=s_mx_e)
            max_num=max_num;

        cout<<"Min :"<<min_num<<" Max :"<<max_num<<endl;
    }

    return 0;
}


My solution is wrong..it doesn't generate correct output.

Please give me some hint..help me to do it.
Last edited on
Topic archived. No new replies allowed.