https://leetcode.com/problems/palindrome-number/description/
The gist of the title: Give an int to determine whether it is a palindrome number.
Problem-solving ideas: look at the solution. Start cutting from the lowest digit of the original number x, and the cut out number is y will. Compare x and y to see if they are equal.
Special case: A negative number is definitely not a palindrome (because of the negative sign), and a number with a 0 at the end is not a palindrome except for 0 (because there can be no 0 in the highest bit other than 0).
Code:
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || x % 10 == 0 && x != 0) return false;
int reverse = 0;
while (x > reverse) {
reverse = reverse * 10 + x % 10;
x /= 10;
}
//第一种情况,原数为偶数位;第二种,原数为奇数位,while退出时会有reverse = x
return (x == reverse || x == reverse / 10);
}
};
python:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0 or x % 10 == 0 and x != 0:
return False
reverse = 0
while x > reverse:
reverse = reverse * 10 + x % 10
x //= 10
return x == reverse or x == reverse // 10