Beginner Number Problems Python

Reverse a Number Program in Python

Reverse the digits of an integer in Python, first with arithmetic and then with string slicing.

  • TimeO(d),
  • SpaceO(1) for the loop, O(d) for slicing
  • Hints3
  • Read2 min
Quick answer

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.

Digit extraction with % and //while loopBuilding a number digit by digitString slicing
1

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.

Input

An integer n.

Output

The number with its digits reversed.

Examples

Example 1
Inputn = 12345
Output54321

The digits 1 2 3 4 5 are read from the end.

Example 2
Inputn = 1200
Output21

The reversed digits are 0021, and leading zeros are dropped in a number.

Example 3
Inputn = -456
Output-654

Reverse 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
2

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 rev is 54 and the next digit is 3, how do you make 543?
  • What should happen to the zeros at the end of 1200?
3

Hints

Open one at a time — try again after each.
1 Hint 1
n % 10 gives the last digit; n // 10 removes it.
2 Hint 2
rev * 10 shifts the digits of rev one place to the left, making room for the new digit.
3 Hint 3
Remember the sign first, reverse abs(n), then multiply the sign back.
4

Approach

Reveal the step-by-step approach

Reverse number using while loop in Python

  1. Set rev = 0.
  2. While n > 0:
    • digit = n % 10 takes the last digit.
    • rev = rev * 10 + digit appends it to rev.
    • n = n // 10 drops it from n.
  3. rev is 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
5

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.

6

Solution

Reveal the full Python solution
solution.py
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.

TimeO(d), where d is the number of digits
SpaceO(1) for the loop, O(d) for slicing
7

Review 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

Practising Python for interviews?

CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us