【问题描述】
Determine whether an integer is a palindrome. Do this without extra space.
【思路】在O(1)的空间复杂度内,因此不能转化为字符串反转字符串。
循环除以10取出最左端数字,mod10取最右端数字,依次进行比较。
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
if (x < 10) {
return true;
}
int base = 1;
while (x / base >= 10) {
base *= 10;
}
while (x != 0) {
int left = x / base;
int right = x % 10;
if (left != right) {
return false;
}
x = (x - left * base) / 10;
base /= 100;
}
return true;
}
}