[LeetCode] Smallest Value of the Rearranged Number

2165. Smallest Value of the Rearranged Number

You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros.

Return the rearranged number with minimal value.

Note that the sign of the number does not change after rearranging the digits.

  • Time : O(log10n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
long long largest(long long n) {
string num = to_string(n);
sort(num.begin(),num.end(), greater<char>());
return -stoll(num);
}
long long smallest(long long n) {
string num = to_string(n);
sort(num.begin(),num.end());
for(int i = 0; i < num.length(); i++) {
if(num[i] != '0') {
swap(num[i], num[0]); break;
}
}
return stoll(num);
}
public:
long long smallestNumber(long long num) {
return num > 0 ? smallest(num) : largest(-num);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/smallest-value-of-the-rearranged-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.