zoukankan      html  css  js  c++  java
  • C实例--推断一个字符串是否是回文数

    回文是指顺读和反读内容均同样的字符串。比如”121”,”ABBA”,”X”等。

    本实例将编写函数推断字符串是否是回文。

    引入两个指针变量,開始时,两个指针分别指向字符串的首末字符,当两个指针所指字符相等时,两个指针分别向后和向前移动一个字符位置,并继续比較。直到两个指针相遇。说明该字符串是回文。如果比較过程中发现两个指针指向的字符不相等,则推断该字符串不是回文。

    以下是代码的实现部分:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define N 20
    
    int Cycle(char *s);
    
    /**
     * 回文是指顺读和反读内容均同样的字符串。比如"121","ABBA","X"等。
     * 本实例将编写函数推断字符串是否是回文。
     *
     */
    int main()
    {
        char s[N];
    
        while(1){
            printf("Please input the string you want to judge(input ^ to quit):
    ");
            scanf("%s",&s);
    
            if(s[0] == '^'){
                break;
            }
    
            if(Cycle(s)){
                printf("%s is a cycle string!
    ",s);
            }else{
                printf("%s is not a cycle string!
    ",s);
            }
        }
    
        return 0;
    }
    
    /**
     * 推断字符串s是否是回文
     *
     * param:
     *  char *s: 被推断的字符串
     * return:
     *  0:      表示字符串s不是回文数
     *  非零:  表示字符串s是回文数
     */
    int Cycle(char *s){
        char *h,*t;
    
        for(h = s,t = s + strlen(s) - 1;t > h;h++,t--)
            if(*h != *t) break;
    
        return t <= h;
    }
    

    以下是程序的执行结果:

    这里写图片描写叙述

    在做这个实例的时候,让我想到了之前有一个实例是推断一个数是否是回文数,是这样做的,如果一个数n=232,从各位数字開始,分别为2,3,2;这些数字分别乘以100,10,1最后相加。比較和原来的数是否相等。就能推断该数书否是回文数字了。

  • 相关阅读:
    AX 2012 Security Framework
    The new concept 'Model' in AX 2012
    How to debug the SSRS report in AX 2012
    Using The 'Report Data Provider' As The Data Source For AX 2012 SSRS Report
    Deploy SSRS Report In AX 2012
    AX 2012 SSRS Report Data Source Type
    《Taurus Database: How to be Fast, Available, and Frugal in the Cloud》阅读笔记
    图分析理论 大纲小结
    一文快速了解Posix IO 缓冲
    #转载备忘# Linux程序调试工具
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5208836.html
Copyright © 2011-2022 走看看