Input: num =310Output: 103Explanation: 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 is103.
Input: num =-7605Output: -7650Explanation: 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.
To minimize the value, rearrange the digits in ascending order for positive numbers (skipping leading zeros), and in descending order for negative numbers (to get the largest absolute value, which is the smallest negative). Handle zeros carefully to avoid leading zeros in the result.
classSolution {
publiclongsmallestNumber(long num) {
if (num == 0) return 0;
char[] arr = Long.toString(Math.abs(num)).toCharArray();
if (num > 0) {
Arrays.sort(arr);
int i = 0;
while (i < arr.length&& arr[i]=='0') i++;
if (i < arr.length) {
char t = arr[0]; arr[0]= arr[i]; arr[i]= t;
}
return Long.parseLong(new String(arr));
} else {
Arrays.sort(arr);
for (int l = 0, r = arr.length- 1; l < r; l++, r--) {
char t = arr[l]; arr[l]= arr[r]; arr[r]= t;
}
return-Long.parseLong(new String(arr));
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funsmallestNumber(num: Long): Long {
if (num ==0L) return0Lval s = Math.abs(num).toString().toCharArray()
if (num > 0) {
s.sort()
var i = 0while (i < s.size && s[i] =='0') i++if (i < s.size) s[0] = s[i].also { s[i] = s[0] }
return String(s).toLong()
} else {
s.sortDescending()
return -String(s).toLong()
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defsmallestNumber(self, num: int) -> int:
if num ==0: return0 s = list(str(abs(num)))
if num >0:
s.sort()
i =0while i < len(s) and s[i] =='0': i +=1if i < len(s): s[0], s[i] = s[i], s[0]
return int(''.join(s))
else:
s.sort(reverse=True)
return-int(''.join(s))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnsmallest_number(num: i64) -> i64 {
if num ==0 { return0; }
letmut s: Vec<char>= num.abs().to_string().chars().collect();
if num >0 {
s.sort();
letmut i =0;
while i < s.len() && s[i] =='0' { i +=1; }
if i < s.len() { s.swap(0, i); }
s.into_iter().collect::<String>().parse().unwrap()
} else {
s.sort_by(|a, b| b.cmp(a));
-s.into_iter().collect::<String>().parse::<i64>().unwrap()
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
smallestNumber(num: number):number {
if (num===0) return0;
lets= Math.abs(num).toString().split("");
if (num>0) {
s.sort();
leti=0;
while (i<s.length&&s[i] ==='0') i++;
if (i<s.length) [s[0], s[i]] = [s[i], s[0]];
return parseInt(s.join(""));
} else {
s.sort((a, b) =>b.localeCompare(a));
return-parseInt(s.join(""));
}
}
}