Reverse a Number Program in Python
Reverse the digits of an integer in Python, first with arithmetic and then with string slicing.
- Time
O(d), - Space
O(1) for the loop, O(d) for slicing - Hints3
- Read2 min
To reverse a number in Python, start with rev = 0 and repeat while n > 0: rev = rev * 10 + n % 10, then n = n // 10. For 12345 this builds 5, 54, 543, 5432 and finally 54321. The shortcut int(str(n)[::-1]) also works for positive numbers, but interviewers usually want the arithmetic loop.
Problem statement
Write a reverse a number program in Python. Given an integer, print its digits in reverse order. For example, 12345 becomes 54321.
Use a while loop with arithmetic first. Then show the string slicing method.
An integer n.
The number with its digits reversed.
Examples
n = 1234554321The digits 1 2 3 4 5 are read from the end.
n = 120021The reversed digits are 0021, and leading zeros are dropped in a number.
n = -456-654Reverse 456 and put the minus sign back.
Constraints
- n can be any integer; handle the sign separately for negative numbers
- Python integers have no fixed size, so there is no overflow
Think before you code
Reveal the questions to ask yourself first
- How do you get the last digit of
n, and how do you remove it? - If
revis 54 and the next digit is 3, how do you make 543? - What should happen to the zeros at the end of 1200?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
Reverse number using while loop in Python
- Set
rev = 0. - While
n > 0:digit = n % 10takes the last digit.rev = rev * 10 + digitappends it torev.n = n // 10drops it fromn.
revis the reversed number.
rev * 10 + digit is the key line. Multiplying by 10 shifts every digit one place
left, and adding digit puts the new digit in the units place.
Reverse integer in Python with slicing
str(n)[::-1] reverses the text, and int() turns it back into a number. It is short,
but it fails on negative numbers, because the - ends up at the end:
int("654-") raises a ValueError.
| Method | Code | Handles negatives? |
|---|---|---|
| Arithmetic loop | rev = rev * 10 + n % 10 |
Yes, with abs() and the sign |
| Slicing | int(str(n)[::-1]) |
No, unless you strip the sign first |
Dry run
Walk through the example step by step
n = 12345, rev = 0:
n | digit = n % 10 | rev = rev * 10 + digit | n // 10
------+----------------+------------------------+--------
12345 | 5 | 5 | 1234
1234 | 4 | 54 | 123
123 | 3 | 543 | 12
12 | 2 | 5432 | 1
1 | 1 | 54321 | 0
n is 0, so the loop stops. The reversed number is 54321.
Solution
Reveal the full Python solution
n = int(input("Enter a number: "))
rev = 0
while n > 0:
digit = n % 10
rev = rev * 10 + digit
n = n // 10
print("Reversed number:", rev)Output:
Enter a number: 12345
Reversed number: 54321
The loop runs once per digit. It uses only arithmetic, so the same code works in C or Java with almost no change.
A function that also handles negatives and zeros
def reverse_number(n):
sign = -1 if n < 0 else 1
n = abs(n)
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n //= 10
return sign * rev
for n in [12345, 1200, 7, 0, -456]:
print(n, "->", reverse_number(n))
12345 -> 54321
1200 -> 21
7 -> 7
0 -> 0
-456 -> -654
1200 becomes 21 because the first two digits added to rev are zeros, and
0 * 10 + 0 is still 0.
The slicing method
n = 12345
print(int(str(n)[::-1]))
print(int(str(1200)[::-1]))
print(str(1200)[::-1])
54321
21
0021
If you need the zeros kept, as in "0021", keep the result as a string. A number
cannot have leading zeros. Slicing is explained in
reverse a string in Python.
Where this is used
Reversing a number is the first step of the palindrome program in Python: a number is a palindrome if it equals its reverse. The digit loop is also the base of the sum of digits program. The Java version of this page is reverse a number without using strings.
O(d), where d is the number of digitsO(1) for the loop, O(d) for slicingReview before the interview
Common mistakes
- Using n / 10 instead of n // 10. In Python 3, / gives a float, and rev gets decimal digits.
- Writing rev = rev + digit * 10 instead of rev = rev * 10 + digit, which does not shift the earlier digits.
- Using int(str(n)[::-1]) on a negative number. The minus sign moves to the end and int() raises ValueError.
- Printing n after the loop and expecting the original. The loop has turned n into 0, so save a copy if you need it.
Edge cases to test
- 0 gives 0, because the loop never runs and rev stays 0.
- Trailing zeros are lost: 1200 becomes 21.
- Negative numbers: reverse abs(n) and multiply the sign back, so -456 gives -654.
Interview follow-ups
- How would you check whether a number is a palindrome using this reverse?
- How would you reverse a 32-bit integer and return 0 if the result overflows, as in LeetCode?
- How would you swap only the first and last digits of a number?
Keep practising
Reverse a Number Without Using Strings
Hints · Dry run · SolutionSolve Similar problemPalindrome Program in Python (Number and String)
Hints · Dry run · SolutionSolve Similar problemSum of Digits Program in Python
Hints · Dry run · SolutionSolve Similar problemSwap the First and Last Digits of a Number
Hints · Dry run · SolutionSolve Related learningLoops In Programming
TutorialLearn Related learningWhat Is Python Used For
TutorialLearn Related learningPython Interview Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising Python for interviews?
CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
