2014/05/27(Tue) 21:48:35 編集(投稿者)
LINQ 解。
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;
}
}