w3resource

Python: Next bigger number by rearranging the digits of a given number


Write a Python program to create the next bigger number by rearranging the digits of a given number.

Sample Solution:

Python Code :

# Define a function 'rearrange_bigger' that takes an integer 'n' as input
def rearrange_bigger(n):
    # Convert the number 'n' into a list of its digits represented as strings
    nums = list(str(n))
    
    # Iterate through the digits from the second-to-last to the first digit
    for i in range(len(nums) - 2, -1, -1):
        # Check if the current digit is less than the next digit
        if nums[i] < nums[i + 1]:
            # Slice the list from the current index to the end and store it in 'z'
            z = nums[i:]
            
            # Find the smallest digit greater than the current digit
            y = min(filter(lambda x: x > z[0], z))
            
            # Remove 'y' from the list 'z'
            z.remove(y)
            
            # Sort the remaining elements in 'z'
            z.sort()
            
            # Rearrange the digits in 'nums' to form the next bigger number
            nums[i:] = [y] + z
            
            # Convert the rearranged list of digits back into an integer and return it
            return int("".join(nums))
    
    # If no bigger number can be formed, return False
    return False

# Test cases to demonstrate the function's behavior with different input numbers

n = 12
print("Original number:", n)
print("Next bigger number:", rearrange_bigger(n))

n = 10
print("\nOriginal number:", n)
print("Next bigger number:", rearrange_bigger(n))

n = 201
print("\nOriginal number:", n)
print("Next bigger number:", rearrange_bigger(n))

n = 102
print("\nOriginal number:", n)
print("Next bigger number:", rearrange_bigger(n))

n = 445
print("\nOriginal number:", n)
print("Next bigger number:", rearrange_bigger(n)) 

Sample Output:

Original number: 12
Next bigger number: 21

Original number: 10
Next bigger number: False

Original number: 201
Next bigger number: 210

Original number: 102
Next bigger number: 120

Original number: 445
Next bigger number: 454

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find numbers within a given range where every number is divisible by every digit it contains.
Next: Write a Python program to find the list with maximum and minimum length using lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.