Python program to sort digits of a number in ascending order
Given an integer N, the task is to sort the digits in ascending order. Print the new number obtained after excluding leading zeroes.
Examples:
Input: N = 193202042
Output: 1222349
Explanation:
Sorting all digits of the given number generates 001222349.
Final number obtained after removal of leading 0s is 1222349.Input: N = 78291342023
Output:1222334789
Approach: Follow the steps below to solve the problem:
- Convert the given integer to its equivalent string
- Sort the characters of the string using join() and sorted().
- Convert string to integer using type casting
- Print the integer obtained.
Below is the implementation of the above approach:
Python3
# Python program to # implement the above approach # Function to sort the digits # present in the number n def getSortedNumber(n): # Convert to equivalent string number = str (n) # Sort the string number = ''.join( sorted (number)) # Convert to equivalent integer number = int (number) # Return the integer return number # Driver Code n = 193202042 print (getSortedNumber(n)) |
1222349
Time Complexity: O(N*log(N))
Auxiliary Space: O(N)
Method#2: Using numpy:
Algorithm :
- Initialize the input number n
- Convert the number to a string representation using str(n)
- Convert the string digits to a list of integers using list comprehension [int(x) for x in str(n)]
- Sort the digits list using numpy sort method np.sort(digits)
- Join the sorted digits as string using ”.join(map(str, np.sort(digits)))
- Convert the sorted digits string back to an integer using int()
- Return the sorted integer
- Print the returned sorted integer
Python3
import numpy as np def getSortedNumber(n): digits = [ int (x) for x in str (n)] number = int (''.join( map ( str , np.sort(digits)))) return number n = 193202042 print (getSortedNumber(n)) #This code is contributed by Jyothi pinjala. |
Output:
1222349
The time complexity : O(n log n), where n is the number of digits in the input number, because the np.sort() function uses a quicksort algorithm, which has an average time complexity of O(n log n).
The auxiliary space : O(n), because we create a list of length n to hold the individual digits of the input number. Additionally, we create a string of length n to hold the sorted digits, and an integer variable to hold the final output. These variables are all constant in size with respect to the input, so they do not contribute to the space complexity.