Given an integer, sort the digits in ascending order and return the new integer.
- Ignore leading zeros.
Parameters:
- Input: num {Integer}
- Output: {Integer}
Constraints:
- Do not convert the integer into a string or other data type.
- Time: O(N) where N is the number of digits.
- Space: O(1)
Examples:
- 8970 --> 789
- 32445 --> 23445
- 10101 --> 111
My code (as follows) works similar to the counting sort:
def sort_digits(n):
digit_counts = {}
result = 0
while n > 0:
digit = n % 10
digit_counts[digit] = digit_counts.get(digit, 0) + 1
n /= 10
power = 0
for i in range(10, -1, -1):
if i in digit_counts:
while digit_counts[i] >= 1:
result += i * (10 ** (power))
power += 1
digit_counts[i] -= 1
return result
Do not convert the integer into a string or other data type.
doesn't make much sense. For example, in your solution, you indirectly encoden
as the dictdigit_counts
, does that count as conversion? I suspect it means "direct" conversion, but that's still a bit silly; more realistic is justreturn the value as an int
. \$\endgroup\$/=
is not a floor divide. \$\endgroup\$