Solution one: common solution
The best solution is to convert the integer to a string first, and then divide the string into an array. You only need to loop half the length of the array to determine whether the corresponding elements are equal.
Code Implementation
Java
///简单粗暴,看看就行
class Solution {
public boolean isPalindrome(int x) {
String reversedStr = (new StringBuilder(x + "")).reverse().toString();
return (x + "").equals(reversedStr);
}
}
Solution 2: Advanced solution-mathematical solution
Through rounding and taking the remainder operation to obtain the corresponding number in the integer for comparison.
For example: the number 1221.
By calculating 1221/1000, the first
bit 1 is obtained. By calculating 1221% 10, the last bit 1
can be compared and
then 22 is taken out to continue the comparison.
Code Implementation
Java
class Solution {
public boolean isPalindrome(int x) {
//边界判断
if (x < 0) return false;
int div = 1;
//
while (x / div >= 10) div *= 10;
while (x > 0) {
int left = x / div;
int right = x % 10;
if (left != right) return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
}
Solution Three: Advanced Solution-Ingenious Solution
Intuitively looking at the number of palindromes, it feels like folding the numbers in half to see if they correspond one-to-one.
So the operation of this solution is to take out the second half of the number and flip it.
One point to note here is that since the number of palindromes can be odd or even, so when its length is even, it should be equal when folded in half; when its length is odd, then after it is folded in half, One length requires one digit to be removed (divide by 10 and rounded).
The specific practices are as follows:
Each time the remainder operation (% 10) is performed, the lowest number is taken out: y = x% 10
The lowest number is added to the end of the number taken out: revertNum = revertNum * 10 + y For
each lowest digit taken, x must be selected from Divide by 10 to
determine whether x is less than revertNum. When it is less, it means that the number has been halved or more than half.
Finally, determine the parity: if it is even, revertNum and x are equal; if it is odd, the middle number Just at the lowest bit of revertNum, divide it by 10 and it should be equal to x.
Code
class Solution {
public boolean isPalindrome(int x) {
//思考:这里大家可以思考一下,为什么末尾为 0 就可以直接返回 false
if (x < 0 || (x % 10 == 0 && x != 0)) return false;
int revertedNumber = 0;
while (x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
return x == revertedNumber || x == revertedNumber / 10;
}
}