In this article we will learn to implement a Java program to find given number is palindrome or not. A Java program is provided below which reads a number and prints whether it is a palindrome or not.
A palindrome is one which is same after reversing it. For example, if you take a number like 1221, after reversing it, it is again 1221.
Following program reads a number from the user and finds out whether it is a palindrome or not:
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = input.nextInt();
int dup = n;
int rev = 0;
while(n != 0)
{
rev = rev * 10 + (n % 10);
n = n / 10;
}
if(rev == dup)
System.out.println("Given number is a palindrome");
else
System.out.println("Given number is not a palindrome");
input.close();
}
}
Input and output for the above program are as follows:
Enter a number:
1225221
Given number is a palindrome
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply