Formatted question description: https://leetcode.ca/all/2165.html

# 2165. Smallest Value of the Rearranged Number (Medium)

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.

Example 1:

Input: num = 310
Output: 103
Explanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310.
The arrangement with the smallest value that does not contain any leading zeros is 103.


Example 2:

Input: num = -7605
Output: -7650
Explanation: Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.
The arrangement with the smallest value that does not contain any leading zeros is -7650.


Constraints:

• -1015 <= num <= 1015

Similar Questions:

## Solution 1.

// OJ: https://leetcode.com/problems/smallest-value-of-the-rearranged-number/

// Time: O(KlogK) where K is the number of digits in n
// Space: O(K)
class Solution {
public:
long long smallestNumber(long long n) {
if (n == 0) return 0;
int sign = n >= 0 ? 1 : -1, zero = 0;
n = abs(n);
vector<int> d;
while (n) {
if (n % 10 == 0) ++zero;
else d.push_back(n % 10);
n /= 10;
}
if (sign == 1) {
sort(begin(d), end(d));
long ans = d;
while (zero--) ans = 10 * ans;
for (int i = 1; i < d.size(); ++i) {
ans = 10 * ans + d[i];
}
return ans;
} else {
sort(begin(d), end(d), greater<>());
long ans = 0;
for (int i = 0; i < d.size(); ++i) {
ans = 10 * ans + d[i];
}
while (zero--) ans = 10 * ans;
return -ans;
}
}
};