How to reverse a number in python
A number can be reversed in python through various methods
1. Using String Slicing
Here the given integer input is converted to string using str(). Then reverse the string through string slicing. Finally the reversed string is converted back into int.
num=int(input()) rev=str(num) print(int(rev[::-1]))
2. Using while loop
In this method, we are using while loop to iterate over the digits of the number by popping them one by one using the modulo operator. These popped digits are appended to form a new number which would be our reversed number.
num = int(input()) reverse = 0 while(num>0): rem = num %10 #modulo operator returns the last digit reverse = (reverse *10) + rem num= num//10 print(reverse)
Please login to comment
View all comments