Python Practice › Basic Programs › Program 24
Reverse a number
Write a Python program to reverse the digits of a number.
Input
12345
Output
54321
Approach
- Take the last digit with
% 10and remove it with// 10. - Build the reversed number digit by digit.
Solution 1: arithmetic
n = 12345reversed_n = 0while n > 0: digit = n % 10 reversed_n = reversed_n * 10 + digit n //= 10print(reversed_n)Output
54321
Line by line
Line 4
n % 10 is the last digit (5 first).
Line 5
Shifting the result one place left (* 10) and adding the digit appends it.
Line 6
//= 10 removes the last digit; the loop ends when n reaches 0.
Solution 2: string slicing
n = 12345print(int(str(n)[::-1]))Output
54321
Line by line
Line 2
Convert to a string, reverse it with [::-1] and convert back to int.
Learn the concept
New to this topic? Read the lesson, then come back.