题目要求只能用O(1)的空间,所以不能考虑把它转化为字符串然后reverse比较的方法。
在提示中也提到了,如果考虑reverse number的方法,可能造成溢出。
每次,取出数的最高位和最低位比较,这里设置一个base为10^n,用来取出数的最高位,每次循环除以100,因为每次数会消去2位。
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
if(x < 10)
return true;
int base = 1;
while(x / base >= 10){
base *= 10;
}
while(x){
int leftDigit = x / base;
int rightDigit = x % 10;
if(leftDigit != rightDigit){
return false;
}
x -= base * leftDigit;
base /= 100;
x /= 10;
}
return true;
}
};
1119

被折叠的 条评论
为什么被折叠?



