Palindromic Numbers – Solution

The challenge for this month’s Exercise is to output the first 100 palindromic numbers, which are integers that reflect the same digits on either side. Rather than devise a complex mathematical equation to determine these values, I cheated.

Yes, just like the prior month’s Exercise (Cyclops numbers), I convert the integer value to a string, then use my handy strrev() function to compare the original with the reversed string. When they match, a palindromic value is found.

Here is the main() function from my solution (the listing omits the strrev() function).

2022_10-Exercise.c

int main()
{
    const int total = 100;
    const int size = 5;        /* assume 5 digits max */
    const int columns = 9;
    int count,v,x,y;
    int results[total];
    char fwd[size+1];        /* +1 for the null char */
    char *bkd;

    /* find the palindromic values */
    count = 0;
    v = 1;
    while(count<total)
    {
        /* eliminate single digits */
        if( v < 10 )
        {
            results[count] = v;
            count++;
        }
        else
        {
            snprintf(fwd,size,"%d",v);
            bkd = strrev(fwd);
            if(strcmp(bkd,fwd) == 0 )
            {
                results[count] = v;
                count++;
            }
        }
        v++;
    }

    /* output the results in a fancy table */
    x = 0;
    while( count )
    {
        for( y=0; y<columns; y++ )
        {
            printf("%5d",results[(x*columns)+y]);
            count--;                /* decrement the count */
            if( !count )            /* if count is zero, stop */
                break;
            if( y<columns-1)
                putchar('\t');
        }
        x++;
        putchar('\n');
    }

    return(0);
}

A while loop counts the palindromic numbers, zero through 100. An if test handles single digit values (v < 10) as these are all considered palindromic.

The else portion of the decision uses the snprintf() function to convert integer v into a string fwd[]. The strrev() function reverses this string into a new string, char pointer bkd. The strcmp function compares the two values in an if decision. When they match, the number is palindromic. Its value is saved in array results[] and variable count is incremented.

The main() function’s second while loop outputs the results in a fancy table. The output is shown in Figure 1.

screen output

Figure 1. Output from my solution, using a table borrowed from last month’s solution.

I’d be curious to see a mathematical solution for this exercise. I assume you could use the modulo operator or perhaps some logarithmic witchcraft to peel off digits from the original integer. But even if you could re-splice these values into a new, reversed integer, how do you test to determine whether the two values are palindromic? Do the eggheads have a solution?

Regardless, I hope your solution, however it’s accomplished, met with success.

Leave a Reply