Python Program to Reverse a Number – 2024

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

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 517

Leave a Reply

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