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:
Below is the implementation of the above approach:
Python3
def getSortedNumber(n):
number = str (n)
number = ''.join( sorted (number))
number = int (number)
return number
n = 193202042
print (getSortedNumber(n))
|
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))
|
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.
Last Updated :
07 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...