Palindrome Number in Java
In this example, You learn about java program for Palindrome. A Palindrome Number is a number that is same after reverse. Example: 121, 343, 101, etc. also a string can be a palindrome such as COC, www, etc.
Palindrome Number Algorithm
- Receive the number to check for palindrome.
- Hold number in variable.
- Reverse the number and store in temporary variable.
- Compare the both hold number and temporary number.
- If both are same then, number is palindrome else not a palindrome number.
Here you learn palindrome program in java, You are given a number and the task of the program to check whether number is palindrome or not.
import java.util.*;
public class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
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 number is a palindrome.");
else
System.out.println("Entered number is not a palindrome.");
}
}
OutputEnter a number 120 Entered number is not a palindrome.
Palindrome Program in Java
import java.util.*;
public class Palindrome
{
public static void main(String args[])
{
String inputString;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
inputString = in.nextLine();
int length = inputString.length();
int i, begin, end, middle;
begin = 0;
end = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
if (inputString.charAt(begin) == inputString.charAt(end)) {
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
System.out.println("Palindrome");
}
else {
System.out.println("Not a palindrome");
}
}
}
OutputEnter a string www Palindrome
Tags:
java