-
Notifications
You must be signed in to change notification settings - Fork 0
/
Exchange_Digits.cpp
93 lines (61 loc) · 1.36 KB
/
Exchange_Digits.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include<bits/stdc++.h>
using namespace std;
#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL)
#define forn(i,n) for (int i = 0; i < int(n); i++)
#define mod 1000000007
#define pb push_back
#define ff first
#define ss second
#define ii pair<int , int>
#define vi vector<int>
#define ll long long
#define INF 1000000005
#define endl '\n'
int main()
{
fast_io;
int a, b;
cin>>a>>b;
vi ar;
while(a>0) {
ar.pb(a%10);
a /= 10;
}
int y = b, b_len=0;
while(y>0) {
b_len++;
y /= 10;
}
// if len(a) < len(b)
if(ar.size() < b_len) {
cout<<-1<<endl;
return 0;
}
// sort the array to get the Least number in lexicographically pattern
sort(ar.begin(), ar.end());
// if len(a) > len(b)
if(ar.size() > b_len) {
int sum=0;
for(int i=0; i<ar.size(); i++) {
sum += ar[ar.size()-i-1]*pow(10,i);
}
cout<<sum<<endl;
return 0;
}
// if len(a) == len(b)
// Generate all permutations
int ans = -1;
do {
int sum=0;
for(int i=0; i<ar.size(); i++) {
sum += ar[ar.size()-i-1]*pow(10,i);
}
if(sum>b) {
ans = sum;
break;
}
} while(next_permutation(ar.begin(), ar.end()));
cout<<ans<<endl;
return 0;
}
// End