How to check a Palindrome Number and a Palindrome string ? A Program to check Palindrome number and palindrome string in C++

Palindrome Number / String

Palindrome :

                                A sequence is called palindrome when it reads same backwards as forwards. While checking for a palindrome number or sequence we check whether the first number matches with last, second number matches with the number second from last and so on. Remember the middle entity will be unique that is it will be a single one only we don't need to compare with any other entity. Now let us see the two methods of checking a palindrome number.
  1.  Using modulo and division operator
  2.  Using String



        

Program to check Palindrome Number using Division and Modulo operator

    In this method we will reverse the given number and compare it with original number to check whether the given number is palindrome or not. 

Logic

  • Input the number
  • Declare a temporary variable and copy the number.
  • Reverse the number using division and modulo operator 
  • Check whether the reversed and original number is same or not
  • If numbers are same print Palindrome else print Not a palindrome

Code 

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int n,temp,rev=0;
    cin>>n;
    temp=n;
    while(temp)
    {
        rev=rev*10+temp%10;
        temp=temp/10;
    }
    if(n==rev)
    {
        cout<<"palindrome";
    }
    else
    {    cout<<"not palindrome";}

    return 0;
}


***

Program to check given string is palindrome or not 

        We can use strings to check our given number is palindrome or not, strings ( word ) uses the same method. We will compare first with last and so on. Follow the code and logic to get a better understanding. 


Logic 

  • Input string
  • Calculate length
  • Take variable to hold index from last
  • In loop check for each index i matches with last index j
  • Run the loop for half of length (till the middle index only)
  • If no match found at any location terminate the loop and print Not palindrome
  • If all the matches are found print Palindrome

Code 

#include <iostream>
using namespace std;

int main() {
    string s;
    cin>>s;
    
    int l = s.length(); 
    int j = l-1;     
    int c = 0;
    
    for(int i = 0;i < l/2; i++){
        if(s[i] == s[j]){ 
            c=0;
        }
        else {
            c=1;
            break;
        }
        j--;
    }
    
    if(c==1) {
        cout<<"Not a palindrome"<<endl;
    }
    else{
        cout<<"Palindrome"<<endl;
    }
}

***




!! SUBSCRIBE FOR MORE CODES & VIDEOS !!

Post a Comment

0 Comments