Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Reverse a Number

Reverse an integer with arithmetic rather than slicing text. Students trace place-value rebuilding, negative-sign restoration, and the loss of trailing zeros.

IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 2 of 14
reverse-a-number.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Reverse number
5reversed_num = 0
6temp = abs(num)
7
8while temp > 0:
9 last_digit = temp % 10
10 reversed_num = reversed_num * 10 + last_digit
11 temp //= 10
12
13# Handle negative
14if num < 0:
15 reversed_num = -reversed_num
16
17print(f"Reversed: {reversed_num}")

Output

Enter a number: 12345
Reversed: 54321

Enter a number: -123
Reversed: -321

In this one

  • Rebuild place values
  • Restore a negative sign
  • Understand lost leading zeros

How it works

  1. 1

    Extract digits from the absolute input.

  2. 2

    Update reversed_num as its old value times ten plus digit.

  3. 3

    Restore the original sign and print the result.

Walk through Reverse a Number

num = 120

  1. 1.Take digit 0: reverse remains 0, temp becomes 12.
  2. 2.Take digit 2: reverse becomes 2, temp becomes 1.
  3. 3.Take digit 1: reverse becomes 21, temp becomes 0.

Edge cases

What is the reverse of 120?

What is the reverse of 120?

21; leading zeros are not stored in an integer.

What is the reverse of -123?

What is the reverse of -123?

-321, because the original sign is restored.

What's going on

reversed_num grows while temp shrinks. Multiplying the partial result by ten opens a units position for the next extracted digit.

For 120, extracted digits zero, two, and one build the numeric result 21. An integer cannot preserve a leading zero. The original sign is restored after the magnitude has been reversed; zero stays zero when its loop is skipped.

What is the reverse of 120? 21; leading zeros are not stored in an integer.

What is the reverse of -123? -321, because the original sign is restored.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why multiply the partial result by ten?

Pick an answer to check it.

Question 2

What is the reverse of 120?

Pick an answer to check it.

Questions people ask

What is the reverse of 120?

21; leading zeros are not stored in an integer.

What is the reverse of -123?

-321, because the original sign is restored.

Why multiply the partial result by ten?

To shift existing digits one place left.