Write a Program to Reverse an Integer Value 54321 Python

Hi, in this article lets try to understand how to reverse an integer number and then try reversing the integer value 54321 as mentioned in the problem statement.

When ever you get an integer reverse problem you should know (Modulus, Addition and Division) MAD technique. 

Take the number and perform modulus by 10 to get last digit of number, add the last digit number to reverse_number and perform division of original number by 10 to take out the last digit.This is how you bring last digit to first.


reverse a number



Lets look in to Python Program to Reverse an Integer Value 54321.

The code has been divided in to three phases, Phase 1 initialize values, Phase 2 Calculate the reverse of integer and Phase 3 print the reverse of a number.

 

Phase 1 : Initialize a number and rev_number to 54321 and 0 respectively

number = 54321

rev_number = 0 


Phase 2 : Until number becomes zero, perform modulus addition and true division. Add last digit by multiplying the rev_number by 10.

while number != 0:

    last_digit = number % 10

    rev_number = rev_number * 10 + last_digit

    number = number // 10


Phase 3 : Print the reverse of a number i.e, rev_number.

print("Reverse of number is : ", rev_number)


Final Program : Below is the complete program to reverse integer 54321 to 12345.

number = 54321

rev_number = 0 

while number != 0:

    last_digit = number % 10

    rev_number = rev_number * 10 + last_digit

    number = number // 10

print("Reverse of number is : ", rev_number)

 

When we run this program we get the below output.

# python sample.py

Reverse of number is :  12345


Conclusion : Hope you understood this program. If interested in more programs do subscribe to my blog.



Post a Comment

0 Comments