Problem
Problem page: https://leetcode.com/problems/palindrome-number/
Topics: Math
Difficulty: Easy
Similar problems: (E) Palindrome Linked List
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
Analysis
I need to check whether a number is a palindrome. A negative number can't be a palindrome, and the numbers 0~9 are all palindromes. The basic idea is to compare the first and last digits each time to see if they match. I can get the last digit by taking the number modulo 10, so the question is how to get the first digit.
Don't try to reverse the whole number, since that can cause overflow. (Though if the number is a palindrome, reversing it won't cause overflow anyway. But if the number isn't a palindrome, could reversing it cause overflow and leave me with the original number???)
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-palindrome-number/
