Palindrome
Number
Determine whether an integer is a palindrome. Do this without extra space.
确定一个整数是不是回文。要求空间复杂度为O(1).
负数不是回文
分析:
首先计算正数是 10 的几次幂,然后分别取最高位和最低位比较,如果不相等则不是回文,相等则去掉最高位和最低位继续进行比较。
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) //负数
{
return false;
}
int temp = x;
int count = 1;
int highDigit = 0;
while(temp/10) //计算是10的几次幂
{
temp /= 10;
count *= 10;
}
while(x)
{
highDigit = x / count; //取得最高位
if(x%10 != highDigit)
{
return false;
}
x = x % count; //去掉最高位
x = x / 10; //去掉最低位
count /= 100; //降低两个数量级
}
return true;
}
};