LeetCode problem #9 — Palindrome number
In this LeetCode challenge we’re asked to determine whether or not a provided number is a palindrome (and as such, I would argue that a better name would be “Check if a number is a palindrome”).
If you’ve read my post on the similar problem #7 (reverse integer) then you can probably see where this is going.
Solution #1: Reverse array
For this incredibly simple solution, we split the input number into an array of numbers, reverse it, and then check if the re-combined value of the reversed array matches the original one.
You can improve performance on this a little by performing a few common palindrome checks to cut out anything you know won’t work, such as numbers less than 0, or numbers above 0 that are divisible by 10. But if you really want to see a performance gain, you’re going to need to drop the use of arrays and employ a more mathematical solution.
Solution #2: Mathematical
This solution, based on LeetCode user choongmanee‘s submission, performs the aforementioned checks for values that don’t require the expensive reversing operation to take place, and then reverses the number using a clever technique that I’m not going to sit here and pretend to understand.
In terms of performance, it’s actually fairly similar, so I’ll leave you to make your own mind up on which you prefer.