C++ での回文プログラム

C++ での回文数プログラム

数が反転しても同じままである場合、それは回文数として知られています。

これを行うには 2 つの方法があります。

  • 文字列反転メソッドの使用
  • モジュロ演算子の使用

文字列リバース メソッドの使用

アルゴリズム:

<オール>
  • 数値を文字列に変換
  • その文字列を別の文字列にコピー
  • 文字列を反転
  • 反転した文字列と元の文字列を比較
  • コード:

    #include<iostream>
    
    #include<cstring> //string library
    
    #include <algorithm> //library containing begin() and end()
    
    using namespace std;
    
    int main()
    
    {
    
    int number,remainder;
    
    cin>>number;
    
    string s1=to_string(number);//storing string value of number in s1
    
    string s2=s1;//copy contents of s1
    
    reverse(s2.begin(), s2.end()); //reversing the complete string s2
    
    if(s1==s2)
    
    cout<<"palindrome";
    
    else
    
    cout<<"not a palindrome";
    
    return 0;
    
    }

    利点:

    • 理解しやすく実行しやすい

    短所:

    • 文字列の変換によるメモリの浪費

    モジュロ演算子の使用

    アルゴリズム:

    <オール>
  • 後で使用するために、別の変数に数値を保存します。
  • 次に、while ループを使用して数値を反転します。
  • 反転した数字と元の数字を比較してください。
  • コード:

    #include<iostream>
    
    using namespace std;
    
    int main()
    
    {
    
    int num,rem;
    
    cin>>num;
    
    int duplicatenum=num;
    
    int newnum=0;
    
    while(num!=0) // till all digits of num are dealt with
    
    {
    
    rem=num%10; //remainder,last digit extracted
    
    newnum=newnum*10+rem; // connect rem to newnum
    
    num=num/10; //trimming last digit from num
    
    }
    
    if(newnum==duplicatenum)
    
    cout<<"palindrome";
    
    else
    
    cout<<"not a palindrome";
    
    return 0;
    
    }

    利点:

    • 迅速な実行
    • 省スペース