49.輸入一字串,檢查是否迴文 (迴文是指正反序相同,如,LeveL)

來源:互聯網
上載者:User

標籤:style   blog   color   使用   os   io   檔案   for   

(1)

#include<iostream>using namespace std;int main(){    int k=0;    int j;    char b[20];    cout<<"please input an number: "<<endl;    cin>>b;    for(j=0;j<20&&b[j]!=‘\0‘ ;j++); //字串有一個結束符,判斷它可知是否結束    {        k=j;    }    for(int m=0;m<k;m++)    {        if(b[m]!=b[k-m-1])        {            cout<<"這不是迴文數!"<<endl;            return -1;//跳出迴圈        } //不能判斷一個就確定是迴文    }    //檢查完畢,是迴文才會到這裡    cout<<"這是迴文數!"<<endl;    return 0;}

(2)

#include<iostream>#include<string.h>//這個標頭檔可以使用strlen函數using namespace std;int main(){    int k=0;    int m,n;    char b[20];    cout<<"please input an number: "<<endl;    cin>>b;    for (m=0,n=strlen(b) - 1; (m!=n) && (m+1!=n); m++, n--)    {        if (b[m] != b[n])        {            cout<<"這不是迴文數!"<<endl;            return -1;//跳出迴圈        }//不能判斷一個就確定是迴文    }    //檢查完畢,是迴文才會到這裡    cout<<"這是迴文數!"<<endl;    return 0;}

(3)運用指標

#include<iostream>#include<string.h>//這個標頭檔可以使用strlen函數using namespace std;int HuiWen(char*);int main(){    int k=0;    int m,n;    char b[20];    cout<<"please input an number: "<<endl;    cin>>b;    if(HuiWen(b))    {        cout<<"這是迴文數";    }else    {        cout<<"這不是迴文數";    }    return 0;}int HuiWen(char* s){    if(NULL == s)    {        return 0;    }    char *head=s;//指向第一個字元    char *tail=s+strlen(s)-1;//指向最後一個字元    while(true)    {        if(head >= tail)return 1;        if(*head == *tail)        {            head++;            tail--;        }        else        {            return 0;        }    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.