Reverse Number Recursively
Reverse an integer by carrying a partial result through recursive calls. Students trace a shrinking argument, an expanding accumulator, and sign restoration.
1def reverse_number(n, rev=0):2 # Base case3 if n == 0:4 return rev56 # Recursive case7 last_digit = n % 108 rev = rev * 10 + last_digit9 return reverse_number(n // 10, rev)1011# Test12num = int(input("Enter a number: "))13result = reverse_number(abs(num))14if num < 0:15 result = -result16print(f"Reversed: {result}")
Output
Enter a number: 12345 Reversed: 54321
In this one
- Carry an accumulator
- Append place-value digits
- Restore the original sign
How it works
- 1
Extract the current units digit.
- 2
Pass n // 10 and rev * 10 + digit onward.
- 3
Return rev at zero, then restore the sign.
Edge cases
What does input zero return?
What does input zero return?
Zero, the initial rev.
What does -120 become?
What does -120 become?
-21 after the sign is restored.
What's going on
rev starts at zero and is updated to rev * 10 + last_digit. The next call receives both the shorter n and that updated accumulator.
At n equal to zero, the function returns the completed rev. Input 120 produces 21 because integers do not retain leading zeros. abs handles the magnitude and the caller restores a negative sign. Pending calls still use stack space.
What does input zero return? Zero, the initial rev.
What does -120 become? -21 after the sign is restored.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does rev hold?
Pick an answer to check it.
Question 2
What does input zero return?
Pick an answer to check it.
Questions people ask
What does input zero return?
Zero, the initial rev.
What does -120 become?
-21 after the sign is restored.
What does rev hold?
The digits rebuilt so far.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum