1. The subject
Given an integer x, return true if x is a palindrome integer; Otherwise, return false.
Palindromes are integers that read in positive (left to right) and backward (right to left) order. For example, 121 is palindrome and 123 is not.
Example 1:
Input: x = 121 Output: true
Example 2:
Input: x = -121 Output: false
Interpretation: Read from left to right as -121. Read from right to left, 121-. So it’s not a palindrome number.
Example 3:
Input: x = 10 Output: false Description: Read from right to left, 01. So it’s not a palindrome number.
Example 4:
Input: x = -101 Output: false
Tip:
- -231 <= x <= 231 – 1
Advanced: Can you solve this problem by not converting integers to strings?
2. The answer
Idea 1:
Converts a number to a string and compares two Pointers
class Solution {
public boolean isPalindrome(int x) {
String xString = String.valueOf(x);
int head = 0;
int tail = xString.length() - 1;
while(head < tail) {
if (xString.charAt(head) != (xString.charAt(tail))) {
return false;
}
head++;
tail--;
}
return true;
}
}
Copy the code
Submission Results:
Idea 2:
What if it’s not a string?
- Take the number directly and compare it with the original number, where negative numbers can be passed directly
- Boundary problem: Can inverted numbers be outside the int range? Can you be lazy and use long😄
The code implementation is as follows:
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
long rx = 0;
int tmp = x;
while (tmp != 0) {
rx = rx * 10 + tmp % 10;
tmp /= 10;
}
return rx == x;
}
}
Copy the code
Submission Results:
If there is any mistake, please point out.