Skip to content

2165. Smallest Value of the Rearranged Number 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  long long smallestNumber(long long num) {
    string s = to_string(abs(num));
    ranges::sort(s, [&](int a, int b) { return num < 0 ? a > b : a < b; });
    if (num > 0)
      swap(s[0], s[s.find_first_not_of('0')]);
    return stoll(s) * (num < 0 ? -1 : 1);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public long smallestNumber(long num) {
    String[] digits = String.valueOf(Math.abs(num)).split("");
    String s = Stream.of(digits).sorted().collect(Collectors.joining());
    StringBuilder sb = new StringBuilder(s);
    if (num <= 0)
      return -1 * Long.parseLong(sb.reverse().toString());
    if (sb.charAt(0) == '0') {
      final int firstNonZeroIndex = sb.lastIndexOf("0") + 1;
      sb.setCharAt(0, sb.charAt(firstNonZeroIndex));
      sb.setCharAt(firstNonZeroIndex, '0');
    }
    return Long.parseLong(sb.toString());
  }
}
1
2
3
4
5
6
class Solution:
  def smallestNumber(self, num: int) -> int:
    s = sorted(str(abs(num)), reverse=num < 0)
    firstNonZeroIndex = next((i for i, c in enumerate(s) if c != '0'), 0)
    s[0], s[firstNonZeroIndex] = s[firstNonZeroIndex], s[0]
    return int(''.join(s)) * (-1 if num < 0 else 1)