Python Program to Reverse a Number Ad Sponsored

ⓘ Sponsored by

Reversing a number means taking an integer and creating a new integer with the same digits in the opposite order. For example, if the input number is 12345, the output would be 54321.

Python Code :

The Below Python program reverses a number:

number = 12345
reverse = 0

while number != 0:
    digit = number % 10
    reverse = reverse * 10 + digit
    number //= 10

print(f'Reverse of the number: {reverse}')

In this program, we first define a number (in this example, 12345). We then define a variable called reverse and initialize it to zero. This variable will hold the reversed number.

We use a while loop to reverse the number. Inside the loop, we use the modulus operator (%) to get the last digit of the number. We then add this digit to the reversed number (reverse) multiplied by 10, shifting the digits one place to the left. Finally, we divide the number by 10 using integer division (//) to remove the last digit.

We continue this process until the number becomes zero, at which point the reversed number is complete.

Finally, we print the reversed number using the print() function.

Note that this program assumes that the input number is a positive integer. If you want to reverse a negative integer or a floating-point number, you will need to modify the program accordingly. Ad Sponsored

ⓘ Sponsored by