Skip to main content
Back to problems
#2165
Medium Algorithms

Smallest value of the rearranged number

Math Sorting
53.4% acceptance
Feb 25, 2026
683
27
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. The sign of the number does not change after rearranging.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn smallest_number(num: i64) -> i64 {
    if num == 0 {
      return 0;
    }
    let negative = num < 0;
    let mut digits: Vec<u8> = num.abs().to_string().into_bytes();
    if negative {
      // Sort descending to get largest absolute value (most negative)
      digits.sort_unstable_by(|a, b| b.cmp(a));
    } else {
      // Sort ascending, but move leading zeros after the first non-zero digit
      digits.sort_unstable();
      // Find first non-zero digit and swap with index 0
      if let Some(pos) = digits.iter().position(|&b| b != b'0') {
        digits.swap(0, pos);
      }
    }
    let s = String::from_utf8(digits).unwrap();
    let result: i64 = s.parse().unwrap();
    if negative { -result } else { result }
  }
}