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.
代码:
// test9PalindromeNumber.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
bool isPalindrome(int x);
int thedivision(int x, int count);
#define INT_MIN (-2147483647 - 1) /* minimum (signed) int value 为了测试-2147483648*/
int _tmain(int argc, _TCHAR* argv[])
{
bool res = isPalindrome(1000000001);
return 0;
}
bool isPalindrome(int x)
{
if (x < (-2147483647)) //边界值处理太麻烦,所以直接返回结果算了
return false;
if (x>=0 && x<10) //个位数,且是非负数,这直接就看出结果了。
return true;
if (x>-10 && x < 0) //个位数,且是负数,这直接就看出结果了。
return false;
int count = 0; //统计X有多少位
int i, j;
int y = x;
int compare = 0; //统计已经比较了多少位
int start = 10;
int signal = -1;//负数为-1,正数就是1了。
if (x > 0)
signal = 1;
int temp1, temp2;
while (y != 0) //统计X有多少位
{
count = count + 1;
y = y / 10;
}
for (j = count, i = 1;compare+1<=count ; j=j-2, i = i * 10)
{
compare += 2;//比较了第一个位和最后一位,所以比较的增加两位。
//此处不敢去掉高位的数字是因为担心像1001的数字,如果减去高位1,则剩下001,这是不合理的。
temp1 = thedivision(x,j);
if (i != 1)
{
if (signal*temp1 < i && signal*temp1 >= 0)
temp1 = 0;
else
temp1 = temp1%10;
}
temp2 = x%10;
if ((signal*temp1) != temp2)
return false;
x = x / 10;
}
return true;
}
int thedivision(int x, int count)
{
for (int i = 1; i < count; i++)
x = x / 10;
return x;
}