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

Check Palindrome Recursively

Check numeric palindromes with a recursive reverse helper. Students compare an unchanged magnitude with an accumulator result and trace the stopping case.

IntermediatePhase 3 - Level 2: Advanced RecursionExample 3 of 10
check-palindrome-recursively.py
1def reverse_number(n, rev=0):
2 if n == 0:
3 return rev
4 last_digit = n % 10
5 rev = rev * 10 + last_digit
6 return reverse_number(n // 10, rev)
7
8# Check palindrome
9num = int(input("Enter a number: "))
10reversed_num = reverse_number(abs(num))
11if abs(num) == reversed_num:
12 print("Palindrome")
13else:
14 print("Not a palindrome")

Output

Enter a number: 121
Palindrome

Enter a number: 123
Not a palindrome

In this one

  • Reuse a recursive reverse
  • Preserve a comparison target
  • Define sign-ignored palindromes

How it works

  1. 1

    Reverse abs(num) through the accumulator helper.

  2. 2

    Wait for its zero base case to return rev.

  3. 3

    Compare that reverse with abs(num).

Edge cases

Does zero pass?

Does zero pass?

Yes. Both magnitude and reverse are zero.

Does -121 pass?

Does -121 pass?

Yes. The code ignores the sign for this comparison.

What's going on

The helper rebuilds reversed digits in rev while dividing n by ten. Its base case returns the accumulated reverse when no digits remain.

The caller compares that result with abs(num), not with a consumed working argument. Thus -121 passes under a sign-ignored definition. Recursive calls keep stack frames until they return, so large digit counts still have a depth limit.

Does zero pass? Yes. Both magnitude and reverse are zero.

Does -121 pass? Yes. The code ignores the sign for this comparison.

Quiz

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

Question 1

What is compared at the end?

Pick an answer to check it.

Question 2

Does zero pass?

Pick an answer to check it.

Questions people ask

Does zero pass?

Yes. Both magnitude and reverse are zero.

Does -121 pass?

Yes. The code ignores the sign for this comparison.

What is compared at the end?

Original magnitude and reversed magnitude.