Reverse a number
Write a Python program to reverse the digits of a number.
12345
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)54321
Line by line
n % 10 is the last digit (5 first).
Shifting the result one place left (* 10) and adding the digit appends it.
//= 10 removes the last digit; the loop ends when n reaches 0.
Solution 2: string slicing
n = 12345print(int(str(n)[::-1]))54321
Line by line
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.