1. Java
public class Solution {
public boolean isPalindrome(int x) {
if(x<0) return false;
return x==reverse(x);
}
public int reverse(int x) {
long sum=0;
for(; x!=0; x = x/10){ // can not be x>0, since x can be <0
sum = sum*10 + x%10;
if(sum>Integer.MAX_VALUE || sum<Integer.MIN_VALUE) return 0;
}
return (int) sum;
}
}
public class Solution {
public boolean isPalindrome(int x) {
if(x<0) return false;
int len = String.valueOf(Math.abs(x)).length()-1;
while(len>0){
int base = (int) Math.pow(10,len);
if(x/base != x%10) return false;
x = (x%base)/10;
len-=2;
}
return true;
}
}
public class Solution {
public boolean isPalindrome(int x) {
if(x<0) return false;
int L = (int)Math.log10(x)+1;
if(L<2) return true;
while(L>=2){
int h = (int)(x/Math.pow(10,L-1));
int t = x%10;
if(h!=t) return false;
x = (int)(x%Math.pow(10,L-1)/10);
L = L-2;
}
return true;
}
}
2. Python:
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0: return False
base=1
while x/base>9:
base=base*10
while base>9:
if x%10 != x/base:
return False
x=x%base
x=x/10
base=base/100
return True