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;
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容