In this post, we’re going to solve LeetCode’s “Palindrome Number” using TypeScript.
Given an integer
x is palindrome integer.
- For example,
121is a palindrome while
-2^31 <= x <= 2^31 - 1
Follow up: Could you solve it without converting the integer to a string?
Our aim is to solve this without converting the integer to a string. If you’re already familiar with our solution for LeetCode’s Reverse Integer, this problem is going to be a breeze because we solved that problem without converting the integer to a string.
But this time, instead of reversing the whole integer, we only have to reverse half of the digits. We can then compare those half, and see if they are the same (palindrome).
And in the case where there are odd numbers of digits in the integer, we can ignore the middle digit because it will always equal to itself.
Translating our approach to code:
That’s it for LeetCode’s “Palindrome Number” 🎉.
You can also find the code on my Github.