Linux, OpenSource, Programming And Hacks

Nov 13, 2016

Python Program to reverse a number using loop

Nov 13, 2016
Here is a simple program to find the reverse of an entered number. Please note that this program works for only positive integers.

Source Code:

x = input("Please Enter a number to reverse: ")
reverse = 0

    reverse = reverse * 10
    reverse = reverse + x % 10
    x = x/10



Please Enter a number to reverse: 12345

Explaination of the logic

In the above given program, we get the reversed number in the reverse variable (initialized to 0) after completing the while loop.

we add the last digit of the number with reverse variable each time in the loop then we get rid of the last digit by diving it with 10.

Let's see the value of reverse variable after each iteration for an example input, say 12345

(2) 5
(3) 54
(4) 543
(5) 5432
(6) 54321

No comments:

Post a Comment