recursionpalindromerecursive-datastructures

Checking an integer is palindrome using recursion without using any extra reverse function


I have been writing a is_palindrome(int num) function which takes an integer and return true or false. I got the idea of reversing the integer and then check it with the original. To do that I need an extra reverse() function. But I want to know if there is a way of checking the palindrome using only one recursive function.


Solution

  • While a recursive algorithm isn't necessary to determine whether or not a number is a palindrome, the simplest recursive one I could think of would be as follows:

    Pseudocode:

    function is_palindrome(i) {
      if (i is a single-digit number) return true
      x = first digit of i
      y = last digit of i
      if (x != y) return false
      if (i is a two-digit number) return true
      j = i without the first and last digit
      return is_palindrome(j)
    }
    

    The algorithm compares the first and last digits, removes them and recursively calls itself with the trimmed number until either all digits have been checked or a mismatch is found.