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).
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).
Here is one more solution in c++ using templates . This solution will work for case insensitive palindrome string comparison .
Why dismiss that solution? It's easy to implement and readable. If you were asked with no computer at hand whether
2**10-23
is a decimal palindrome, you'd surely test it by writing it out in decimal.In Python at least, the slogan 'string operations are slower than arithmetic' is actually false. I compared Smink's arithmetical algorithm to simple string reversal
int(str(i)[::-1])
. There was no significant difference in speed - it happened string reversal was marginally faster.In low level languages (C/C++) the slogan might hold, but one risks overflow errors with large numbers.
Results in seconds (lower is better):
Recursive solution in ruby, without converting the number to string
Fastest way I know: