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).
In Python, there is a fast, iterative way.
This also prevents memory issues with recursion (like StackOverflow error in Java)
I answered the Euler problem using a very brute-forcy way. Naturally, there was a much smarter algorithm at display when I got to the new unlocked associated forum thread. Namely, a member who went by the handle Begoner had such a novel approach, that I decided to reimplement my solution using his algorithm. His version was in Python (using nested loops) and I reimplemented it in Clojure (using a single loop/recur).
Here for your amusement:
There were Common Lisp answers as well, but they were ungrokable to me.
A number is palindromic if its string representation is palindromic:
To check the given number is Palindrome or not (Java Code)
I didn't notice any answers that solved this problem using no extra space, i.e., all solutions I saw either used a string, or another integer to reverse the number, or some other data structures.
Although languages like Java wrap around on integer overflow, this behavior is undefined in languages like C. [Try reversing 2147483647 (Integer.MAX_VALUE) in Java] Workaround could to be to use a long or something but, stylistically, I don't quite like that approach.
Now, the concept of a palindromic number is that the number should read the same forwards and backwards. Great. Using this information, we can compare the first digit and the last digit. Trick is, for the first digit, we need the order of the number. Say, 12321. Dividing this by 10000 would get us the leading 1. The trailing 1 can be retrieved by taking the mod with 10. Now, to reduce this to 232.
(12321 % 10000)/10 = (2321)/10 = 232
. And now, the 10000 would need to be reduced by a factor of 2. So, now on to the Java code...Edited as per Hardik's suggestion to cover the cases where there are zeroes in the number.