Pages

Palindromicity of Integers in C#

In my software engineering course, we were assigned to create a function that will test for the palindromicity of a an integer. My first try is as follows:

static bool palindromicity(int n)
{
    return n.ToString() == new String(n.ToString().Reverse().ToArray()));
}

I know mine is not as efficient as could be, because I am reversing the entire number instead of just the final half. After examination by the professor, however, my function was incorrect and so were the code samples of the entire class. The defect was that a conversion to string was used, when the professor stated that we must use integers.

Here is my next try:

static bool palindromicity(int n)
{
    if (n < 0) return false;
    else if (n < 10) return true;
    else
    {
        int head;
        int tail;
        for (int m = Convert.ToInt32(Math.Pow(10, Math.Floor(Math.Log10(Convert.ToDouble(n))))); n > 9; m /= 100)
        {
            head = n / m;
            tail = n % 10;
            if (head != tail)
                return false;
            n -= m * head;
            n /= 10;
        }
        return true;
    }
}
EDIT: After further inspection of my function, I realized that I made an error. In the for-loop, I made the limit n > 10. this can be an issue if the reduction of n leads to 10. To fix this, I changed the limit to n > 9.

0 comments:

Post a Comment