Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determing Palindrome from uint Input

Given the following:

protected bool IsPalindrome(uint x) // Samples: 1221, 456653
{

}

What's the best approach to determine if the input is a palindrome? Initially, I was trying out arrays by putting the input number into an array, reversing it in a for loop and assigning it to a temp array for comparison. However the indexing syntax got messy real fast, so I decided to simply treat the uint as a string.

Would the following be a valid solution in an interview whiteboard situation, or am I still over-complicating it?

protected 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;

    if (givenNum == testString)
        return true;
    else
        return false;
}
like image 324
IrishChieftain Avatar asked Aug 16 '26 19:08

IrishChieftain


2 Answers

Turn the number into a string, and if that string is equal to its reverse, it's a palindrome:

protected bool IsPalindrome(uint x) { 
    string test = x.ToString();
    string tset = new string(test.ToCharArray().Reverse().ToArray());
    return test == tset;
}
like image 60
Traveling Tech Guy Avatar answered Aug 19 '26 09:08

Traveling Tech Guy


For efficiency you can do the following to get the reverse numerically and compare

protected bool IsPalindrome(uint x)
{
    uint original = x;
    uint reverse = 0;
    while (x > 0) 
    {
        reverse *= 10;
        reverse += x % 10;
        x /= 10;
    }

    return original == reverse;
}
like image 35
juharr Avatar answered Aug 19 '26 09:08

juharr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!