Reverse a Number in Python: 2 Easy Methods
In Python, you can reverse a number using the following methods:
Option one: Utilize string reversal.
- Convert the numbers into strings.
- Reverse the string using slicing functionality with strings.
- Convert the reversed string into an integer.
Example code:
num = 12345
reversed_num = int(str(num)[::-1])
print(reversed_num)
Option 2: Utilize loops and modulo operations.
- opposite_num
- opposite number
- Divide the original number by 10 to remove the last digit.
- Repeat steps 2 and 3 until the original number becomes 0.
- num reversed
Example code:
num = 12345
reversed_num = 0
while num > 0:
reversed_num = reversed_num * 10 + num % 10
num = num // 10
print(reversed_num)
The reversal of numbers can be achieved through methods such as string reversal or looping with modulo. The choice of method depends on personal preference and needs.