Rearranging the given number to form the smallest number in Python

In this article, we will implement a program to rearrange the digits of a given number to form the smallest possible number in Python. We will rearrange the number such that it forms the smallest with the number and the number digits same as the given number.

Examples

Input: 412308
Output: 102348

Input: 028182012
Output: 10122288

Method 1: 

1. Firstly convert the given number into the string using the str() function.

2. Then sort the string and join them like n = ”.join(sorted(n)).

3. Traverse the string n and find the first non zero element in this string n

  • If n[i] == 0 the increase the i value by 1

4. Finally, swap the n[i] with n[0] and return the n value.

def rearrage(n):
    n = ''.join(sorted(n))
    i = 0
    while(n[i] == '0'):
        i += 1
    a = list(n)
    temp = a[0]
    a[0] = a[i]
    a[i] = temp
    n = ''.join(a)
    return n
n = int(input("Enter the n value: "))
print(rearrage(str(n)))

Output

Enter the n value: 028182012
10122288

Enter the n value: 412308
102348

Method 2:

1. Firstly convert integer n into list of string i.e. l = list(str(n))

2. Traverse the list l i.e. enumerate(l)

  • Find the first non-zero element.

3. Append it in the front of string and return the result.

def rearrage(l):
    for i, n in enumerate(l):
        if n != '0':
            temp = l.pop(i)
            break

    return str(temp)+ ''.join(l)

n = int(input("Enter the n value: "))
l = list(str(n))
l.sort()
print("Smallest number formed by rearranging is: ", rearrage(l))

Output

Enter the n value: 98760345678
Smallest number formed by rearranging is: 30456677889

Enter the n value: 00128301
Smallest number formed by rearranging is: 101238

Also, read

Leave a Reply

Your email address will not be published.