leetcode 009-Palindrome Number

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;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容