Palindrome Number
Problem
Given an integer x
, return true
if x
is a palindrome, and false
otherwise.
Follow up: Could you solve it without converting the integer to a string?
Constraints
-231 <= x <= 231 -1
Solution
The problem Palindrome Number
can be solved by reversing digits of given integer and checking if it’s the same as the original. One thing to note here is that since negative integers can never be a palindrome, it should be handled at the beginning.
Implementation
class Solution
{
public:
bool isPalindrome(int x)
{
if (x < 0)
return false;
long int rev = 0;
int y = x;
while (y)
{
rev = rev * 10 + y % 10;
y /= 10;
}
return (long int)x == rev;
}
};