The title
Given an integer x, return true if x is a palindrome; Otherwise, return false.
Palindromes are integers that are read in the same order (from left to right) and in the same order (from right to left). For example, 121 is a palindrome, while 123 is not.
Example 1:
Input: x = 121 Output: trueCopy the code
Example 2:
Input: x = -121 Output: false Description: Read -121 from left to right. Read from right to left: 121-. So it's not a palindrome number.Copy the code
Example 3:
Input: x = 10 Output: false Description: Read from right to left, as 01. So it's not a palindrome number.Copy the code
Example 4:
Input: x = -101 Output: falseCopy the code
implementation
Just turn the numbers around and see if the numbers before and after the comparison are the same.
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) return false;
int temp = x, rev = 0;
while (temp > 0){
rev = rev * 10 + temp % 10;
temp = temp / 10;
}
returnrev == x; }}Copy the code