-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtmp2.cpp
More file actions
41 lines (38 loc) · 1.14 KB
/
tmp2.cpp
File metadata and controls
41 lines (38 loc) · 1.14 KB
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
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
// Function to find the smallest permutation for the track number
int smallestPermutation(int num) {
string s = to_string(abs(num));
vector<char> digits(s.begin(), s.end());
if (num < 0) {
// Negative number: largest permutation, as negative sign makes it smallest
sort(digits.rbegin(), digits.rend());
string result = "";
for (char d : digits) result += d;
return -stoi(result);
} else {
// Positive number: smallest permutation, no leading zero
sort(digits.begin(), digits.end());
// Move leading zero(s) behind first non-zero
if (digits[0] == '0') {
for (int i = 1; i < digits.size(); ++i) {
if (digits[i] != '0') {
swap(digits[0], digits[i]);
break;
}
}
}
string result = "";
for (char d : digits) result += d;
return stoi(result);
}
}
int main() {
int num;
cin >> num;
cout << smallestPermutation(num) << endl;
return 0;
}