直接转换成字符串,然后 reverse 比较一下。但是题目中有写:
进阶:你能不将整数转为字符串来解决这个问题吗?
所以肯定不能使用这种方式!
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x > 0 && x % 10 ==0)) {
return false;
}
StringBuilder sb = new StringBuilder(String.valueOf(x));
return sb.toString().equals(sb.reverse().toString());
}
}
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x > 0 && x % 10 ==0)) {
return false;
}
int res = 0;
int tmp = x;
while (tmp != 0) {
int i = tmp % 10;
res = res * 10 + i;
tmp = tmp / 10;
}
return res == x;
}
}
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x > 0 && x % 10 == 0)) {
return false;
}
int res = 0;
int tmp = x;
while (tmp > res) {
res = res * 10 + tmp % 10;
tmp = tmp / 10;
}
return tmp == res || tmp == res / 10;
}
}
- <End /> -