LeetCode: Palindrome Number With TypeScript
Oct 26, 2022 · 2 min readIn this post, we’re going to solve LeetCode’s “Palindrome Number” using TypeScript.
Problem
Given an integer x
, return true
if x
is palindrome integer.
- For example,
121
is a palindrome while123
is not.
Example 1:
Example 2:
Example 3:
Constraints:
-2^31 <= x <= 2^31 - 1
Follow up: Could you solve it without converting the integer to a string?
Approach
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.
Solution
Translating our approach to code:
Wrap Up
That’s it for LeetCode’s “Palindrome Number” 🎉.
You can also find the code on my Github.