palindrome using cpp code example

Example 1: check if a string is palindrome cpp

// Check whether the string is a palindrome or not.
#include <bits/stdc++.h>

using namespace std;

int main(){
    string s;
    cin >> s;
    
    int l = 0;
    int h = s.length()-1;

    while(h > l){
        if(s[l++] != s[h--]){
            cout << "Not a palindrome" << endl;
            return 0;
        }
    }
    cout << "Is a palindrome" << endl;
    return 0;

}

Example 2: next palindrome number in cpp

#include <iostream>


bool isPalindrome (int number) {
    int decomposed = number, reversed = 0;
    while (decomposed) {
        reversed = 10 * reversed + (decomposed % 10);
        decomposed /= 10;
    }
    return reversed == number;
}


int nextPalindromicNumber (int number) {
    while (!isPalindrome(++number));
    return number;
}


int main () {
    int testCases;
    std::cin >> testCases;
    while (testCases--) {
        int number;
        std::cin >> number;
        std::cout << nextPalindromicNumber(number) << '\n';
    }
}

Example 3: next palindrome number in cpp

#include <iostream>
#include <string.h>
using namespace std;
int nextpalin (int num){
    while (num++) {
        string str = to_string (num); /// int to string conversion
        int l = str.length()-1;
        int s = 0;
        while( s<l ){
              if (str[s]!=str[l]) break;
              else {
                    s++;
                    l--;
                    }
        if (s>=l) return num;}
                }
   }

int main () {
    int t;
    cin >> t;
    while (t--){
    int num;
    cin >> num;
    if (num==0)  cout << "1" << endl;
   else { 
       if (num<9)  cout << num+1 << endl;
       else  cout << nextpalin( num) << endl;}
     }
}

Tags:

Cpp Example