Palindrome Function in Python

1.What is Palindrome

A Palindrome is a word or phrase that is spelled the same even in the backward direction. (ignoring spacing, punctuations, and capitalization)

A Palindrome No. is a number that remains the same even after reversing Ex:.161,24542,848, 38983. It is also a string or sequence of characters i.e. it has the same sequence of letters when reading forwards and backward direction. Example :

  • racecar
  • tenet
  • rotor
  • madam

2.What is a Palindrome Number

Palindrome no. is the number that remains the same when its digits get reversed. Ex: 15451, for example: If we take 131 and reverse it then after reversing the number remains the same.

Steps to Palindrome Number program

  • Input the number from the user.
  • Then Reverse it.
  • Compare the number with the number entered by the user.
  • If both the no.’s are the same then print the number as a palindrome
  • Else print not a palindrome.

Java program to check whether the number is palindrome or Not

Palindrome Number Program in Java

import java.util.Scanner;
 class expalindrome 
{
public static void main(String args[]) 
{
int x,number, y=0,temp=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter any number: ");
number=s.nextInt();
x=number;
while(number>0)
{
x=number%10;
number=number/10;
temp=temp*10+x;
}
if(temp==y)
{
System.out.println("Number is Palindrome");
}
else
{
System.out.println("not Palindrome");
}
}
}

Output

Enter any Number :

161

Number is Palindrome

Flow Chart :

3.What is a Palindrome String

A Palindrome String is a string when read in a forward or backward direction remains the same.

public class Palindrome
{
    public static void main(String args[])
    {
        String x, y = "";
       Scanner a = new Scanner(System.in);
      System.out.print("Enter  string you want to check:");
     x = a.nextLine();
        int l = x.length();
       for(int k = l - 1; k >= 0; k--)
     {
          y = y + x.charAt(k);
      }
      if(x.equalsIgnoreCase(y))
        {
            System.out.println("The string is palindrome.");
        }
        else
        {
            System. out.println("The string is not a palindrome.");
        }
    }
}

Output:

Enter the string you want to check:

NeveroddorEVen

The string is a palindrome.

4.What is a Palindrome Phrase

Palindrome may consist of a Sentence or Phrase  Ex: Mr. Kate ate my Silver worm”, “Do John see God?” . Punctuation, capital letters, and spaces are usually ignored for Ex: “cats live on no evil star”  and “Steps on no cats” include the spaces.

Java program to find if a sentence is a palindrome

public class GFG 
{ 
    // To check sentence is palindrome or not 
    static boolean sentencePalindrome(String str) 
    {     
        int j = 0; 
        int i = str.length()-1; 
          
        // Lowercase string 
        str = str.toLowerCase(); 
          
        // Compares character until they are equal 
        while(j <= i) 
        { 
              
            char getAtj = str.charAt(j); 
            char getAti = str.charAt(i); 
              
            // If there is another symbol in left 
            // of sentence 
            if (!(getAtj >= 'a' && getAtj <= 'z')) 
                j++; 
              
            // If there is another symbol in right  
            // of sentence 
            else if(!(getAti >= 'a' && getAti <= 'z')) 
                i--; 
              
            // If characters are equal 
            else if( getAtj == getAti) 
            { 
                j++; 
                i--; 
            } 
              
            // If characters are not equal then 
            // sentence is not palindrome 
            else 
                return false; 
        } 
          
        // Returns true if sentence is palindrome 
        return true;     
    } 
      
    // Driver program to test sentencePallindrome() 
    public static void main(String[] args)  
    { 
        String str = "Too hot to hoot."; 
        if( sentencePalindrome(str)) 
          System.out.println("Sentence is palindrome"); 
        else
          System.out.println("Sentence is not" + " " + 
                                         "palindrome"); 
    } 
}

5.Palindrome Examples

Palindrome examples :

MANAM
MADAM
b1221b
Rubber
DAD
223454322

Program to check Palindrome string using for loop

public class Main 
{
    public static void main(String[] args) 
    {
        System.out.println( isPalindromeString("Check Palindrome String") );
        System.out.println( isPalindromeString("pbcbp") );
    }
 
         public static boolean is palindrome string(String OrgString) 
 
    {
        String rev = "";
      
        int leng = OrgString.length();
         
        for ( int ip = length - 1; ip >= 0; ip-- )
            rev = rev + OrgString.charAt(ip);
         
        return OrgString.equals(rev);
    }
}

Output : 
False
True

Java Program to check for palindrome number using for loop

package com.javacodegeeks.snippets.basics;
 
public class PalindromeNumber {
 public static void main(String[] args) {
 int numbers[] = new int[]{ 353, 54, 77, 1244, 88, 8967 };
          
        for (int ip = 0; ip < numbers.length; ip++) {
            int numbToCheck = numbers[ip];
            int numbInReverse = 0;
            int temp = 0;
            while (numbToCheck > 0) {
                temp = numbToCheck % 10;
                numbToCheck = numbToCheck / 10;
                numbInReverse = numbInReverse * 10 + temp;
            }
            if (numbers[ip] == numbInReverse) {
                System.out.println(numbers[ip] + " is a palindrome");
            }
            else {
                System.out.println(numbers[ip] + " is NOT a palindrome");
            }
           
        }
 
    }
 }

Output:

353 is a palindrome
54 is NOT a palindrome
77 is a palindrome
1244 is NOT a palindrome
88 is a palindrome
8967 is NOT a palindrome

6.Palindrome in Java Algorithm

Consider an example to check if a No. is a palindrome or not.  A Number is a palindrome if it remains unchanged even when it is reversed, for example, “141” is a palindrome as its reverse is “141”.

Algorithm for Palindrome Number:

 step 1:Set st=0

step 2: Read numb

step 3: Set a=numb

step 4: Repeat through the step-7 until (numb > 0)

step 5: rev=numb%10

step 6: st=(st*10)+rev

step 7: numb=numb/10

step 8: If a equals to st then print” a is a palindrome”

Else print” a is not a palindrome”

step 9: Exit

 Above implementation in Java
Example  Palindrome Number

import java.util.Scanner; 
 public class PalindromeNumb 
 { 
                 public static void main(String args[]) 
             { 
                       int numb,e,f,g; 

                 Scanner st=new Scanner(System.in); 

                 System.out.print("Enter a No. : "); 

                 numb=st.nextInt(); 

                 g=numb; 

                 f=0; 

                 while(numb!=0) 
                       { 
                          e=numb%10; 
                          f=(f*10)+e; 
                          numb=numb/10; 
                        } 

  if(f==g)  

 System.out.println(g+ " & "+ f + " are same, it’s a Palindrome"); 

 else
 
 System.out.println(g+ " & " + f + " aren’t  same,  it’s not aPalindrome"); 

  }
 
 } 
 
  1. (a) Palindrome in Java Code using while loop
     

Java Program example to check whether no. is palindrome or not using while loop

public class Palindromeexample 
{

public static void main(String args[]) 
{

int remdr, reverse= 0, temp;
int k=121; 

temp = k;

// reversed integer is stored in variable
while( k != 0 )
{
remdr= k % 10;
reverse= reverse * 10 + remdr;
k=k/10;
}

if (temp == reverse)
System.out.println(temp + " is a palindrome.");
else
System.out.println(temp + " is not a palindrome.");
}
}

Output: 141 is a palindrome number

Explanation: enter the number which you want to check and store it in a temporary(i.e. temp) variable and reverse the entered number and compare it whether the temp number is the same as the reversed number or different. If both the numbers are similar, it will print the number as a palindrome, else it will print not a palindrome number.

Java Program example to check whether a string is a palindrome or not using while loop :

 
// Java implementation of the approach 
public class PalString { 
  
  
  static boolean is a palindrome(String str) 
    { 
  
        int j = 0; 
        int k = str.length() - 1; 
  
        while (j < k) { 
  
            // if not matching 
            if (str.charAt(j) != str.charAt(k)) 
                return false; 
  
            j++; 
            k--; 
        } 
  
   } 
  
       public static void main(String[] args) 
    { 
        String str = "Great"; 
  
        if (isPalindrome(str)) 
            System.out.print("Yes, string is palindrome"); 
        else
            System.out.print("No, string not isn’t palindrome"); 
    } 
} 



Output:

No, the string isn’t a palindrome

7(b). Using reverse Function

Java Program to reverse a No. and examine whether  the No. is a palindrome or not 

Input : Number =26344362

Output:  Reverse of Number= Yes, it is a palindrome

Input : Number = 65476572465

Output: Reverse of No: 56427567456

Iterative Algorithm :

Input:  No.

1. Initialize revs_numb = 0

2. Loop while numb > 0

     a. Multiply revs_numb by 10 and add numb  % 10 to revs_numb

               revs_numb  = revs_numb*10 + numb %10;

     b. Divide numb by 10

3. Return revs_numb

Example:

numb = 1234

revs_numb= 0

revs_numb = revs_numb *10 + numb%10 = 4

numb = numb/10 = 123

revs_numb = revs_numb*10 + numb%10 = 20 + 6 = 43

numb = numb/10 = 12

revs_number = revs_numb*10 + numb%10 = 260 + 5 = 432

numb = numb/10 = 1

revs_numb = revs_numb*10 + numb%10 = 265 + 4 = 4321

numb = numb/10 = 0

Java Code : 

 
Public class RevFunc { 
  
    static int RevNum(int n) 
    { 
        int revse_n = 0; 
        while (n > 0) { 
            revse_n = revse_n * 10 + n % 10; 
            n = n / 10; 
        } 
        return revse_n; 
    } 
  
    public static void main(String[] args) 
    { 
        int n = 223464322; 
        int revsN = RevNum (n); 
        System.out.println("Reverse of n = " + revsN); 
        
      
        if (n == revsN) 
            System.out.println("Yes, It is palindrome"); 
        else
            System.out.println("No, It is not Palindrome"); 
    } 
}

Output

The reverse of n = 223464322

 Yes, it is a palindrome

8.Check if a Linked List is a Palindrome

https://www.geeksforgeeks.org/wp-content/uploads/2009/08/Palindrome-Linked-List.gif

Mentioned above the single linked list characters, below the function that returns true if the given list is palindrome else returns false.

Method: 1 (Using Stack)

  • To use a stack list of nodes involves 3 steps :
  • Given the list is traversed from head to tail and pushing visited node to stack
  • The list again traversed. Every visited node, pop a node from the stack and compare data of popped node with currently visited node.
  • If all nodes matched return true else false.

Java code for the above approach.

 
import java.util.*;
 
public class LinkList {
    public static void main(String args[])
    {
        Node one = new Node(1);
        Node two = new Node(2);
        Node three = new Node(3);
        Node four = new Node(4);
        Node five = new Node(3);
        Node six = new Node(2);
        Node seven = new Node(1);
        one.ptr = two;
        two.ptr = three;
        three.ptr = four;
        four.ptr = five;
        five.ptr = six;
        six.ptr = seven;
        boolean condition = isPalindrome(one);
        System.out.println("isPalidrome :" + condition);
    }
    static boolean isPalindrome(Node head)
    {
 
        Node slow = head;
        boolean ispalin = true;
        Stack<Integer> stack = new Stack<Integer>();
 
        while (slow != null) {
            stack.push(slow.data);
            slow = slow.ptr;
        }
 
        while (head != null) {
 
            int i = stack.pop();
            if (head.data == i) {
                ispalin = true;
            }
            else {
                ispalin = false;
                break;
            }
            head = head.ptr;
        }
        return ispalin;
    }
}
 
class Node {
    int data;
    Node ptr;
    Node(int d)
    {
        ptr = null;
        data = d;
    }
}

Output 

 isPalindrome: true

METHOD: 2 ( Reversing  list) 
1) take the middle of the linked list. 
2) Reverse the 2nd  half of the linked list. 
3) Check if the 1st half and 2nd  half are identical. 
4) Build the original linked list by reversing the 2nd  half again and attaching it back to the Ist half

Public class LinkList {
    Node head; 
    Node slow_ptr, fast_ptr, second_half;
 
    
    class Node {
        char data;
        Node next;
 
        Node(char d)
        {
            data = d;
            next = null;
        }
    }
 
      boolean is a palindrome(Node head)
    {
        slow_ptr = head;
        fast_ptr = head;
        Node prev_of_slow_ptr = head;
        Node midnode = null; 
        boolean res = true; 
 
        if (head != null && head.next != null) {
                    while (fast_ptr != null && fast_ptr.next != null) {
                fast_ptr = fast_ptr.next.next;
                prev_of_slow_ptr = slow_ptr;
                slow_ptr = slow_ptr.next;
            }
 
             if (fast_ptr != null) {
                midnode = slow_ptr;
                slow_ptr = slow_ptr.next;
            }
 
            second_half = slow_ptr;
            prev_of_slow_ptr.next = null; 
            reverse(); 
            res = compareLists(head, second_half); 
 
            
            reverse(); 
 
            if (midnode != null) {
                prev_of_slow_ptr.next = midnode;
                midnode.next = second_half;
            }
            else
                prev_of_slow_ptr.next = second_half;
        }
        return res;
    }
 
      void reverse()
    {
        Node prev = null;
        Node current = second_half;
        Node next;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        second_half = prev;
    }
 
    boolean compareLists(Node head1, Node head2)
    {
        Node temp1 = head1;
        Node temp2 = head2;
 
        while (temp1 != null && temp2 != null) {
            if (temp1.data == temp2.data) {
                temp1 = temp1.next;
                temp2 = temp2.next;
            }
            else
                return false;
        }
 
        if (temp1 == null && temp2 == null)
            return true;
 
  
      return false;
    }
 
    public void push(char new_data)
    {
  
      Node new_node = new Node(new_data);
 
        new_node.next = head;
 
        head = new_node;
    }
 
    void printList(Node ptr)
    {
        while (ptr != null) {
            System.out.print(ptr.data + "->");
            ptr = ptr.next;
        }
        System.out.println("NULL");
    }
 
    public static void main(String[] args)
    {
 
       LinkList llist = new LinkList();
 
        char str[] = { 'l', 'm', 'n', 'c', 'l', 'm', 'n' };
        String string = new String(str);
        for (int ap = 0; ap < 7; ap++) {
            llist.push(str[ap]);
            llist.printList(llist.head);
            if (llist.isPalindrome(llist.head) != false) {
                System.out.println("Is Palindrome");
                System.out.println("");
            }
            else {
                System.out.println("Not Palindrome");
                System.out.println("");
            }
        }
    }
}

Output: 

a->NULL

Is Palindrome

b->a->NULL

Not Palindrome

a->b->a->NULL

Is Palindrome

c->a->b->a->NULL

Not Palindrome

a->c->a->b->a->NULL

Not Palindrome

b->a->c->a->b->a->NULL

Not Palindrome

a->b->a->c->a->b->a->NULL

Is Palindrome

0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

7 + six =