不用转为字符串:
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) return false;
long tmp = 0;
auto num = x; //先保存x的值
while(x){
tmp = 10*tmp + x%10;
x = x/10;
}
return tmp == num;
}
};
可以加上这一条:
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
反转一半的思路:
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0 || (x % 10 == 0 && x != 0)) return false; //这一步得有
int tmp = 0;
while(x > tmp){
tmp = 10*tmp + x%10;
x = x/10;
}
return x == tmp || x == tmp/10;;
}
};