Given a non-negative integer n, return the smallest possible integer that can be formed using its decimal digits. Treat the digits as a multiset: every digit of n is used exactly once, repeats included.
The result should not have leading zeros unless the number itself is 0.
Function Signature
def smallest_number(n: int) -> int:
Rules
-
Each digit is used exactly as many times as it appears in
n
. No digit may be added or dropped.
-
The result has no leading zeros, so it has the same number of digits as
n
. The only exception is
n = 0
, whose answer is
0
.
-
Return the result as an integer.
Constraints
Examples
Input: n = 310
Output: 103
The digits are 3, 1 and 0. The number cannot start with 0, so the smallest allowed first digit is 1, followed by the remaining digits 0 and 3 in ascending order.
Input: n = 9876
Output: 6789
There is no zero, so arranging the digits 9, 8, 7, 6 in ascending order gives 6789.
Input: n = 1020
Output: 1002
The non-zero digits are 1 and 2, so the number starts with 1. The other arrangements that start with 1 are 1020 and 1200, and both are larger than 1002.