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;
}
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With