求一个字符串是否为回文 编写程序,判断一个字符串是否为“回文”(顺读和逆读都一样的 字符串称为“回文”

如题所述

第1个回答  2010-09-26
#include <stdio.h>
#include <conio.h>
#include <math.h>

int main()
{
int a[20]; //数组从1开始,0舍弃
int num,lenth,n,i,b=0,c=0,p;
// n是每一位数所在数组的编号;i用来判断是否为回文数;p用来打印数组进行验证

printf( "请输入一个至少为三位数的数字\n ");
scanf( "%d ",&num);
printf( "请输入%d的位数\n ",num);
scanf( "%d ",&lenth);

while (num <100) /*必须输入一个三位以上的整数*/
{
printf( "请输入一个至少为三位数的数字\n ");
scanf( "%d ",&num);
}

for (n=1;n <=(lenth-1);n++) //分解所输入数除最高位的每一位数
{
a[n]=num%((int)pow(10,n))/(pow(10,n-1));
printf( "a[%d]= %d\n ",n,a[n]); //打印每一位的数字
}
a[lenth]=num/(pow(10,lenth-1)); //读取最高位
printf( "a[%d]= %d\n ",lenth,a[lenth]); //打印最高位

//以下是判断所输入数字是否为回文数
if (lenth%2==0) //为偶数位时
{
for (i=1;i <=(lenth/2);i++)
{
if (a[i]==a[lenth+1-i]) b++;
}

if (b==(lenth/2))
printf( "%d 是回文数 ",num);
else
printf( "%d 不是回文数 ",num);

}
else //为奇数位时
{
for(i=1;i <=((lenth-1)/2);i++)
if (a[i]==a[lenth+1-i]) c++;

if (c==((lenth-1)/2))
printf( "%d 是回文数 ",num);
else
printf( "%d 不是回文数 ",num);
}

getch();
return 0;
}
第2个回答  2010-09-26
import javax.swing.JOptionPane;
public class Ex5_6
{
public static void main(String[] args)
{
int i=0,flag=0;
String s=JOptionPane.showInputDialog(null,"输入一字符串:","例:",JOptionPane.QUESTION_MESSAGE);
String output=" ";
if(comp(s))
output+=s+"是回文";
else
output+=s+"不是回文";
JOptionPane.showMessageDialog(null,output,"例:",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
public static boolean comp(String s)
{
int i=0;
char[] charArray=s.toCharArray();
while(i<s.length()/2)
{
if(charArray[i]!= charArray[s.length()-1-i])
return false;
i++;
}
return true;
}
}本回答被提问者和网友采纳
第3个回答  2010-09-26
数组从1开始,0舍弃
相似回答