Disclaimer: I was recently asked this in an interview and quickly found myself dealing with some very messy indexing syntax using arrays. I decided to revisit the problem later to see if my initial hunch of treating the uint input as a string would tend toward a cleaner solution.

/// <summary>
/// Input treated as a string for simplification 
/// </summary>
/// <param name="x"></param>
/// <returns>bool</returns>
public static bool IsPalindrome(uint x)
{
    string givenNum = Convert.ToString(x);
    char[] input = givenNum.ToCharArray();    
    Array.Reverse(input);   

    string testString = String.Empty;
    foreach (char a in input)
        testString += a;

    return givenNum == testString;
}


It works fine but I still thought it was a little more verbose than it could be so I posted this question on Stack Overflow and got some very interesting responses. I eventually went with the following solution; since a uint was specifically specified as a parameter, it would seem that an interviewer would be looking for a numerical, non-string answer.

public static bool IsPalindrome(uint x)
{
    uint original = x;
    uint reverse = 0;

    while (x > 0)
    {
        reverse *= 10;
        reverse += x % 10;
        x /= 10;
    }
    return original == reverse;
}



Pingbacks and trackbacks (1)+