Friday, September 14, 2007

Integer Palindromes

File this one under "Silly, Simple Code Snippet Of The Day"™...

Several times on various programming forums, I've seen question about how to find out if an integer value is a palindrome or not (the number is the same "forwards" and "backwards"; e.g., 71317 would be a palindrome, while 71316 would not). Most of the suggested solutions revolve around converting the integer value to a string and reversing the characters. This makes sense, given that "71317" is just a character representation of a number, and many language APIs have ready-made facilities for reversing strings of characters (or at least arrays). That said, finding out if a number is a palindrome using basic math is dead simple, too. Here's a base-10 example in C#:
    using System.Diagnostics;

class ScratchUtils
public static int Reverse(int i)
int result = 0;
while (i != 0)
result = (result * 10) + (i % 10);
i /= 10;
return result;

public static bool IsPalindrome(int i)
return i == Reverse(i);

public static void Main()
Debug.Assert( 0 == Reverse(0));
Debug.Assert( 1 == Reverse(1));
Debug.Assert( 21 == Reverse(12));
Debug.Assert(-21 == Reverse(-12));


No comments:

Post a Comment