Determine whether an integer is a palindrome. Do this without extra space.
分析:由于题目已经要求不能使用额外空间,故不可以把数字转换为字符串s,然后对s取反得到s',判断两字符串是否相等。解决方案是用循环直接将数字取反,最后将得到的新数字与原始数字比较。
#include <stdio.h>
#include <stdbool.h>
bool isPalindrome(int x){
int a = x, r = 0;
if(x < 0)
return false;
while(a > 0){
r = r * 10 + a % 10;
a = a / 10;
}
return r == x;
}
int main(void){
int num;
puts("Enter an integer:");
scanf("%d", &num);
if(isPalindrome(num))
printf("%d is palindrome number\n", num);
else
printf("%d is not a palindrome number\n", num);
return 0;
}