in O(1) space
compare the most significant and the least significant digit and then take them from x
public class Solution {
public boolean isPalindrome(int x) {
/*
* edge cases:
* 1. negative ?
* 2. 1001001? what to do with the 0's
*/
//step 1: find the largest y s.t. 10^y <= x
if(x < 0) return false;
int xx = x;
int base = 1;
while(xx >= 10){
xx = xx/10;
base = base*10;
}
int upper = base;
while(upper > 0){
int most = x/upper;
int least = x%10;
if(most != least) return false;
x = x - most*upper;
x = x/10;
upper = upper/100;
}
return true;
}
}
the time complexity is O(1), too, because an int type in Java has fixed length in decimal.