方式一(将整数转换为字符串,在转换为字符数组):
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
char[] chars = new String(Integer.toString(x)).toCharArray();
int length = chars.length;
for (int i = 0; i < length / 2; i++) {
if (chars[i] != chars[length - 1 - i]) {
return false;
}
}
return true;
}
方式二(将整数的后半部分取反)
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
if (x != 0 && x % 10 == 0) {
return false;
}
int res = 0;
while (x > res) {
res = res * 10 + x % 10;
x /= 10;
}
return x == res || res / 10 == x;
}