Search code examples
cstringrecursionpalindrome

Checking if digits in a string are symmetric (in edges)


I have a string of numbers. I need to check if the numbers on the edges are symmetric, meaning they have the same remainder when modulo by 2.

I have written a code which works, but I have something troubling my mind about that, after some failures I've come up with this code:

int PaliPair(char* st, int n)
{
  if(n<=1) return 1;
  return (*st%2 == *(st+n-1)%2) && PaliPair(st +1, n-2);
}

The question is, why do I have to return n-2 and not n-1? I'm kinda confused of why it works. Any explanation would be highly appreciated. I think I'm missing something, perhaps the fact that the string ends with "\0" which I need to conclude from that something.


Solution

  • If you have a string for example like this

    "1243"
    

    then you at first check the first and the last characters.

    Then you need to check the characters in the middle that is

    "24"
    

    So the target string now has length 4 - 2 (the number of characters that were already checked)

    So in each recursion you check 2 characters, In the next recursion you need to check 2 less characters.

    As for the function itself I would write it like

    int PaliPair( const char *s, size_t n )
    {
       return n < 2 || *s % 2 == *( s + n - 1 ) % 2 && PaliPair( s + 1, n - 2 );
    }
    

    Or even like

    int PaliPair( const char *s, size_t n )
    {
       return n < 2 || ( *s - '0' ) % 2 == ( *( s + n - 1 ) - '0' ) % 2 && PaliPair( s + 1, n - 2 );
    }