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

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.

IntermediatePhase 3 - Level 2: Advanced RecursionExample 2 of 10
reverse-number-recursively.py
1def reverse_number(n, rev=0):
2 # Base case
3 if n == 0:
4 return rev
5
6 # Recursive case
7 last_digit = n % 10
8 rev = rev * 10 + last_digit
9 return reverse_number(n // 10, rev)
10
11# Test
12num = int(input("Enter a number: "))
13result = reverse_number(abs(num))
14if num < 0:
15 result = -result
16print(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. 1

    Extract the current units digit.

  2. 2

    Pass n // 10 and rev * 10 + digit onward.

  3. 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.