Python Program to Reverse a Number – 2022

Machine Learning Projects

Hey guys, in this blog we will see a Python Program to Reverse a Number.

Example 1: Reverse a Number using a while loop

num = int(input('Enter a number -> '))
reversed_num = 0

while num != 0:
    digit = num % 10
    reversed_num = reversed_num * 10 + digit
    num //= 10

print("Reversed Number: " + str(reversed_num))

Output

Enter a number -> 7042
Reversed Number: 2407
  • This is the most commonly used algorithm for reversing a number.
  • In this, we keep on extracting the last number from our main number and keep on adding it to our reversed number.
  • The flow is something like the below:

curr = 7042 ; digit = 0 ; reverse = 0
curr = 704 ; digit = 2 ; reverse = 0 x 10 + 2 = 2
curr = 70 ; digit = 4 ; reverse = 2 x 10 + 4 = 24
curr = 7 ; digit = 0 ; reverse = 24 x 10 + 0 = 240
curr = 0 ; digit = 7 ; reverse = 240 x 10 + 7 = 2407

Example 2: Using String slicing

num = int(input('Enter a number -> '))
print(str(num)[::-1])

Output

Enter a number -> 7042
2407
  • Here we have reversed the number using string operations.
  • First of all, we converted the number to a string and then reversed the string using [::-1].

Check out our other python programming examples

Leave a Comment

Your email address will not be published. Required fields are marked *