Skip to content

Instantly share code, notes, and snippets.

@hidori
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hidori/db0db6d38451cba06b86 to your computer and use it in GitHub Desktop.
Save hidori/db0db6d38451cba06b86 to your computer and use it in GitHub Desktop.
static void Main()
{
var values = new[] { -12321, -123, -121, -12, -1, 0, 1, 12, 121, 123, 12321 };
var query = values.Select(value => new { Value = value, IsPalindrome = IsPalindrome(value) });
foreach(var item in query)
{
Console.WriteLine("{0}: {1}", item.Value, item.IsPalindrome);
}
}
static bool IsPalindrome(int value)
{
if (value < 0) value = -value;
if (0 <= value && value < 10) return true;
var array = ToSequence(value).ToArray();
var length = array.Length;
for(var i = 0; i < length / 2; i++)
{
if (array[i] != array[length - i - 1]) return false;
}
return true;
}
static IEnumerable<byte> ToSequence(int value)
{
if (value < 0) throw new ArgumentOutOfRangeException("value");
if (0 <= value && value < 10)
{
yield return (byte)value;
yield break;
}
while (value > 0)
{
yield return (byte)(value % 10);
value = value / 10;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment