- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathnextSimilar.cpp
38 lines (32 loc) · 774 Bytes
/
nextSimilar.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
// Given a number A in a form of string.
// You have to find the smallest number that has same set of digits as A and is greater than A.
// If A is the greatest possible number with its set of digits, then return -1.
#include<bits/stdc++.h>
usingnamespacestd;
intmain()
{
string A;
cin >> A;
int n = A.length();
int i;
for (i = n - 1; i > 0; i--)
{
if (A[i] > A[i - 1])
break;
}
if (i == 0)
{
cout << -1 << endl;
return0;
}
int x = A[i - 1], smallest = i;
for (int j = i + 1; j < n; j++)
{
if (A[j] > x && A[j] < A[smallest])
smallest = j;
}
swap(A[smallest], A[i - 1]);
sort(A.begin() + i, A.end());
cout << A << endl;
return0;
}