题目:
Determine whether an integer is a palindrome. Do this without extra space.
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
思路:计算正整数的位数,然后根据位数比较,距离对称两边的数字是否相等。
Attention: 计算最高位和最低位数字的方法(对称点)很巧妙。先得到待求位的余数(待求位是最高位),然后取商,得到待求位数字!!
算法复杂度: O(lg(x))
AC Code:
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0)
return false;
long long d = 10, e = 10;
//计算d的初始值,使得x % d = x;
while (x / d) d *= 10;
while (d > e)
{
//计算最高位和最低位数字的方法(对称点)很巧妙。先得到待求位的余数(待求位是最高位),然后取商,得到待求位数字
if ((x % d) / (d / 10) != (x % e) / (e / 10))
return false;
d /= 10;
e *= 10;
}
return true;
}
};
Error Code:
思路同解法一,但是没有找到合适的取到每一位数字的方法。
class Solution {
public:
bool isPalindrome(int x) {
//判断一个整数是否是回溯数字 Palindrome 并且不能使用额外的存储空间
//思路:计算正整数的位数,然后根据位数比较,距离对称两边的数字是否相等。
//假设负整数不是回溯数字
if(x < 0)
return false;
int numDigits, tmp;
numDigits = 0;
tmp = x;
//使用do while,考虑x为0的情况
do
{
tmp /= 10;
numDigits++;
}while(tmp);
for(int i = 1; i <= numDigits/2; i++)
{
int lvalue, rvalue;
//求较小位的数字
//tmp = x % (pow(10, i));
//取余得到数字的方法不正确,1121 % 100 = 21, 21 % 10 = 1, 1不是待求的十位数字2.
tmp = x / (10^(i-1));
while(tmp > 10)
{
tmp %= 10;
}
rvalue = tmp;
//求较大为的数字
//tmp = x % (pow(10, numDigits - i);
tmp = x / (10^(numDigits -i));
/*while(tmp > 10)
{
tmp /= 10;
} */
lvalue = tmp;
if(lvalue != rvalue)
return false;
}
return true;
}
};
解法二:代码更加简洁,思路也简单。
思路:计算反转的数字,然后比较是否相同。
Attention: 计算反转数字的方法很巧妙。从最低位开始,每次*10,(同时待求数字直接去掉最低位,quotient /=10)往前推进,再得到次低位。。重复。
复杂度: O(lg(x))
AC Code:
class Solution {
public:
bool isPalindrome(int x) {
//计算翻转的数字
if( x < 0)
return false;
int reversed = 0;
int reminder, quotient = x;
//计算翻转数字reversed
do
{
reminder = quotient % 10;
quotient /= 10;
reversed = reversed * 10 + reminder;
}while(quotient);
return(reversed == x);
}
};