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.
1# Take number2num = int(input("Enter a number: "))34# Reverse number5reversed_num = 06temp = abs(num)78while temp > 0:9 last_digit = temp % 1010 reversed_num = reversed_num * 10 + last_digit11 temp //= 101213# Handle negative14if num < 0:15 reversed_num = -reversed_num1617print(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
Extract digits from the absolute input.
- 2
Update reversed_num as its old value times ten plus digit.
- 3
Restore the original sign and print the result.
Walk through Reverse a Number
num = 120
- 1.Take digit 0: reverse remains 0, temp becomes 12.
- 2.Take digit 2: reverse becomes 2, temp becomes 1.
- 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.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum