How do I check if a number is a palindrome?

Esteban Araya picture Esteban Araya · Oct 14, 2008 · Viewed 215.4k times · Source

How do I check if a number is a palindrome?

Any language. Any algorithm. (except the algorithm of making the number a string and then reversing the string).

Answer

Jorge Ferreira picture Jorge Ferreira · Oct 14, 2008

For any given number:

n = num;
rev = 0;
while (num > 0)
{
    dig = num % 10;
    rev = rev * 10 + dig;
    num = num / 10;
}

If n == rev then num is a palindrome:

cout << "Number " << (n == rev ? "IS" : "IS NOT") << " a palindrome" << endl;