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).
A lot of the solutions posted here reverses the integer and stores it in a variable which uses extra space which is
O(n)
, but here is a solution withO(1)
space.This is one of the Project Euler problems. When I solved it in Haskell I did exactly what you suggest, convert the number to a String. It's then trivial to check that the string is a pallindrome. If it performs well enough, then why bother making it more complex? Being a pallindrome is a lexical property rather than a mathematical one.
Works for integers only. It's unclear from the problem statement if floating point numbers or leading zeros need to be considered.
Push each individual digit onto a stack, then pop them off. If it's the same forwards and back, it's a palindrome.
Recursive way, not very efficient, just provide an option
(Python code)
Here is a solution usings lists as stacks in python :
popping the stack only considers the rightmost side of the number for comparison and it fails fast to reduce checks