回文型题目解题思路

A4. 回文

在这里插入图片描述

#include  <stdio.h>
#include  <string.h>
#include  <ctype.h>
int fun(char  *s)
{ char  *lp,*rp;
/**********found**********/
  lp= __1__ ;
  rp=s+strlen(s)-1;
  while((toupper(*lp)==toupper(*rp)) && (lp<rp) ) {
/**********found**********/
     lp++; rp __2__ ; }
/**********found**********/
  if(lp<rp) __3__ ;
  else   return 1;
}
void main()
{ char  s[81];
  printf("Enter a string:  ");  scanf("%s",s);
  if(fun(s)) printf("\n\"%s\" is a Palindrome.\n\n",s);
  else printf("\n\"%s\" isn't a Palindrome.\n\n",s);
}


修改后

#include  <stdio.h>
#include  <string.h>
#include  <ctype.h>
int fun(char  *s)
{ char  *lp,*rp;
/**********found**********/
  lp= s ;
  rp=s+strlen(s)-1;
  while((toupper(*lp)==toupper(*rp)) && (lp<rp) ) {
/**********found**********/
	  lp++; rp--;
  };
/**********found**********/
  if(lp<rp) return 0;
  else   return 1;
}
void main()
{ char  s[81];
  printf("Enter a string:  ");  scanf("%s",s);
  if(fun(s)) printf("\n\"%s\" is a Palindrome.\n\n",s);
  else printf("\n\"%s\" isn't a Palindrome.\n\n",s);
}


考察知识点

(1)指针起始地址,函数fun中,对变量lp和rp可知,lp指向形参s起始地址,rp指向s终止地址,故填空1应为s;
(2)每循环一次头指针++,尾指针–。rp指向尾指针,故得
(3)逻辑判断

  if(lp<rp) __3__ ;
  else   return 1;

可得return 0;
实际上,lp与rp相等时,可推得回文

void main()
{ char  s[81];
  printf("Enter a string:  ");  scanf("%s",s);
  if(fun(s)) printf("\n\"%s\" is a Palindrome.\n\n",s);
  else printf("\n\"%s\" isn't a Palindrome.\n\n",s);
}

学习一下:
toupper()将小写字母转换为大写字母
返回值:
如果转换成功,那么返回与 c 对应的大写字母;如果转换失败,那么直接返回 c(值未变)。

C53.回文

在这里插入图片描述
雕虫小技

正儿八经

#include <stdio.h>
#define N 80
int fun(char *str)
{
}

void main()
{
	 char s[N];
	 FILE *out;
         char *test[]={"1234321","123421","123321","abcdCBA"};
	 int i;
	 printf("Enter a string : ");
	 gets(s);
	 printf("\n\n");
	 puts(s);
	 if(fun(s))
		printf("YES\n");
	 else
		printf("NO\n"); 
	 /************************************/
	 out=fopen("out.dat","w");
	 for(i=0;i<4;i++)
	 	if(fun(test[i]))
			fprintf(out,"YES\n");
		else
			fprintf(out,"NO\n");
	 fclose(out);
	 /************************************/
}

在这里插入图片描述
思路1:

int fun(char *str)
{
	int i = 0, k=0,flag=1;
	char  *t;
	t = str;
	while (*t)
	{
		t++;
		k++;
	}

	for (i = 0; i < k / 2; i++)
	{
		if (str[i] == str[k - 1 - i])
			;
		else
		{
			flag = 0;
			break;
		}
	}
	return flag;
}

思路2:

int fun(char *str)
{
	char  *f, *t;

	f = str;
	t = str + strlen(str) - 1;
	while ((*f == *t) && (f < t)) {
		f++; t--;
	};

	if (f < t) return 0;
	else   return 1;
}

难度等级:★★★★★☆☆☆☆
学点啥

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值