problem:
Determine whether an integer is a palindrome. Do this without extra space.
Difficulty:Easy
hints:
- 负数不能为一个回文
- 使用char*来存放单个数值
#include<stdio.h>
#include<stdbool.h>
#include<malloc.h>
bool isPalindrome(int x) {
if(x < 0){
return false;
}
int count = 0,i,temp = x;
while(temp){
count++;
temp = temp / 10;
}
char *c = (char*)malloc(count*sizeof(char));
for(i = 0;i < count ;i++){
c[i] = x%10;
x /= 10;
}
for(i = 0;i < count / 2;i++){
if(c[i]!= c[count-i-1]){
return false;
}
}
return true;
}
int main(){
bool flag = isPalindrome(10);
printf("%d",flag);
}
hints:
- 使用一个整型变量存放一半位数的x最后再和x进行比较
if(x < 0 || (x % 10 == 0 && x != 0)){
return false;
}
int reverse = 0;
while(x > reverse){
reverse = reverse * 10 + x %10;
x = x / 10;
}
return x == reverse || x == reverse / 10;