Example:
To Check if a number is Palindrome:
import java.util.Scanner;
/**
* Java program to check if number is palindrome or not.
* A number is called palindrome if number and its reverse is equal
* This Java program can also be used to reverse a number in Java
*/
public class PolyndromeExample{
public static void main(String args[]){
System.out.println("Please Enter a number : ");
int palindrome = new Scanner(System.in).nextInt();
if(isPalindrome(palindrome)){
System.out.println("Number : " + palindrome + " is a palindrome");
}else{
System.out.println("Number : " + palindrome + " is not a palindrome");
}
}
/*
* Java method to check if number is palindrome or not
*/
public static boolean isPalindrome(int number) {
int palindrome = number;
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
if (number == reverse) {
return true;
}
return false;
}
}
To Check if a String is Palindrome:
A string is a palindrome if it remains unchanged when reversed, for example "dad" is a palindrome as reverse of "dad" is "dad" whereas "program" is not a palindrome.
import java.util.*;
* Java program to check if number is palindrome or not.
* A number is called palindrome if number and its reverse is equal
* This Java program can also be used to reverse a number in Java
*/
public class PolyndromeExample{
public static void main(String args[]){
System.out.println("Please Enter a number : ");
int palindrome = new Scanner(System.in).nextInt();
if(isPalindrome(palindrome)){
System.out.println("Number : " + palindrome + " is a palindrome");
}else{
System.out.println("Number : " + palindrome + " is not a palindrome");
}
}
/*
* Java method to check if number is palindrome or not
*/
public static boolean isPalindrome(int number) {
int palindrome = number;
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
if (number == reverse) {
return true;
}
return false;
}
}
To Check if a String is Palindrome:
A string is a palindrome if it remains unchanged when reversed, for example "dad" is a palindrome as reverse of "dad" is "dad" whereas "program" is not a palindrome.
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse="";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
No comments:
Post a Comment