题目9:
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
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.
/***************************************************************************************************
* (c) Copyright 1992-2015 Embedded Products Research Center
* All Rights Reserved
*
*\File main.c
*\Description Palindrome Number 判断一个数是否为回文
*\Note
*\Log 2015.07.28 Ver 1.0
* 创建文件。
***************************************************************************************************/
#include <stdio.h>
/***************************************************************************************************
*\Function GetLen
*\Description 返回数x的十进制长度
*\Parameter x
*\Return int
*\Note
*\Log 2015.07.28 Ver 1.0
* 创建函数。
***************************************************************************************************/
int isPalindrome(int x)
{
int len = 1; /* x十进制位数 */
int left = 0;
int right = 0;
int temp_x = x;
int max_mul = 1;
int time = 0;
/* 小于0判定为非回文 */
if (x < 0)
{
return 0;
}
/* 一位数直接返回true */
if (x >= 0 && x <= 9)
{
return 1;
}
/* 计算x十进制长度 */
while (temp_x /= 10)
{
len++;
max_mul *= 10;
}
temp_x = x;
/* 需要比较的次数 */
time = len / 2;
while (time)
{
/* 比较最高位和最低位是否相同 */
left = temp_x / max_mul; /* 获取最高位 */
right = temp_x % 10; /* 获取最低位 */
if (left == right)
{
time--;
temp_x = temp_x % max_mul; /* 去掉最高位 */
temp_x = temp_x / 10; /* 去掉最低位 */
max_mul /= 100;
}
else
{
return 0;
}
}
return 1;
}
void main()
{
int x = 123321;
printf("%d\n", (isPalindrome(x)?1 : 0));
getchar();
}