Palindrome of Number / Palindrome of String or Reverse a String Program in Java


Palindrome number in java: A palindrome number is a number that is same after reverse. For example 545, 151, 34543, 343, 171, 48984 are the palindrome numbers.
Palindrome number algorithm
  • Get the number to check for palindrome
  • Hold the number in temporary variable
  • Reverse the number
  • Compare the temporary number with reversed number
  • If both numbers are same, print "palindrome number"
  • Else print "not palindrome number"
Let's see the palindrome program in java. In this java program, we will get a number variable and check whether number is palindrome or not.
  1. class PalindromeExample{  
  1.  public static void main(String args[]){  
  1.   int r,sum=0,temp;    
  1.   int n=454;//It is the number variable to be checked for palindrome  
  1.   
  1.   temp=n;    
  1.   while(n>0){    
  1.    r=n%10;  //getting remainder  
  1.    sum=(sum*10)+r;    
  1.    n=n/10;    
  1.   }    
  1.   if(temp==sum)    
  1.    System.out.println("palindrome number ");    
  1.   else    
  1.    System.out.println("not palindrome");    
  1. }  
  1. }  
Output:

palindrome number


Palindrome of String or reverse a String.


import java.util.Scanner;
public class PalindromeString{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the string which you want to check whether that is palindrome or not: ");
        String s = in.next();
        String r = "";
        for(int i=s.length()-1; i>=0; i--){
            r = r+s.charAt(i);
        }
        System.out.println("Reverse of entered string "+s+" is "+r);
        if(r.equals(s)){
            System.out.println("String "+s+" is palindrome.");
        }else{
            System.out.println("String "+s+" is not palindrome.");
        }
    }
}

Output:

Enter the string which you want to check whether that is palindrome or not:
selenium
Reverse of entered string selenium is muineles
String selenium is not palindrome.

No comments:

Post a Comment

Floyd Triangle

Note- Floyd Triangle is like 1 2 3 4 5 6 7 8 9 10 ------------ import java.util.Scanner; public class FloydTria...

Popular Post