Open In App

Python program to sort digits of a number in ascending order

Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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))


Output

1222349

Time Complexity: O(N*log(N))
Auxiliary Space: O(N)

Method#2: Using numpy:

Algorithm :

  1. Initialize the input number n
  2. Convert the number to a string representation using str(n)
  3. Convert the string digits to a list of integers using list comprehension [int(x) for x in str(n)]
  4. Sort the digits list using numpy sort method np.sort(digits)
  5. Join the sorted digits as string using ”.join(map(str, np.sort(digits)))
  6. Convert the sorted digits string back to an integer using int()
  7. Return the sorted integer
  8. 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.



Last Updated : 07 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads