leetcode 009-Palindrome Number

problem:

Determine whether an integer is a palindrome. Do this without extra space.

Difficulty:Easy

hints:

  • 負數(shù)不能為一個回文
  • 使用char*來存放單個數(shù)值
#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:

  • 使用一個整型變量存放一半位數(shù)的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;
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容