題目描述:
判斷一個整數(shù)是否是回文數(shù)?;匚臄?shù)是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數(shù)。
示例
輸入: 121
輸出: true
C語言答題模板
bool isPalindrome(int x) {
}
解答
由于C語言中沒有布爾類型,所以我們要自己定義stdbool.h頭文件并導(dǎo)入程序中
stdbool.h頭文件如下:
#ifndef __STDBOOL_H
#define __STDBOOL_H
typedef enum{
false = 0,
true = !false,
}bool;
#endif
然后把該文件放入安裝路徑的XXXX\VC98\Include中即可
完整代碼
#include <stdio.h>
#include <stdbool.h>
bool isPalindrome(int x)
{
int temp,k;
k = x;
temp = 0;
if(x<=0)
return false;
while(x)
{
temp = temp*10 + x%10;
x = x /10;
}
if(k==temp)
return true;
else
return false;
}
int main()
{
int m;
scanf("%d",&m);
if(isPalindrome(m))
printf("%d是回文數(shù)\n",m);
else
printf("%d不是回文數(shù)\n",m);
return 0;
}
另一種方式就是先判斷出該整數(shù)的位數(shù),然后再接著判斷第一位和最后一位是否相同,第二位和倒數(shù)第二位是否相同........
#include <stdio.h>
#include <stdbool.h>
bool isPalindrome(int x)
{
int a[10];
int i,j;
i=0;
if(x<0)
return false;
while(x)
{
a[i] = x%10;
x = x/10;
i++;
}
for(j=0;j<i;j++)
{
if(a[j]==a[i-j-1])
{
return true;
}
else
return false;
}
}
int main()
{
int m;
scanf("%d",&m);
if(isPalindrome(m))
printf("%d是回文數(shù)\n",m);
else
printf("%d不是回文數(shù)\n",m);
return 0;
}